python -database connection(part III)

 we have done basic creation of Mysql database creation by using python code. if you didn't see our last site, don't feel awful click folks.

now, we will use Flask for connecting python with a web browser. 



                            










What is Flask?

              Flask is one kind of package which contains, connectivity to the webserver and makes the responsive website. Most of the python backend projects are solved by using Flask, Django method. These two methods are having the ability to make responsive websites.

here, we won't be creating any big website, we gonna make a tiny form to store the data in our backend DB.


for making the Flask website we have to download these packages present on this site(r u looking for these packages am I rt?)


lets, we create a form first.


<html>

<head> <title> data operations </title> </head>

<body>

    <form  method="post" action ="http://localhost:5000/store" >

        tentative number < input type="text" name="ten">

       <p></p>

</br>

        name  < input type="text" name="name">

        <p></p>

 </br>

        college name< input type="text" name="clg">

        <p></p>

        operations: <select name="op">

 

            <option value="insert">insert</option>

            < option value="delete">delete</option>

            < option value="update">update</option>

          </select> <p></p>

          < button name="but">Submit</button>

    </form>

</body>

 

</html>



the above code belongs to the Form code. after running this code you will get a form.


while you are doing flask application, you should store your index.html file in the templates folder. 
if you didn't store your HTML file in templates folder, your application won't be called your HTML files. 

why we have to store HTML files on this folder is, if we are making any kind of website connection, that times we need to save each coding file in a separate folder, like templates/HTML or templates/CSS.
this is the perfect manner to store all the web application code.

now, we will move to app.py.

first, we have to import first all the packages required for this app.

from flask import *;

from  flask_mysqldb import MySQL

import MySQLdb.cursors


below code is structure of the Flask application. This same structure is only maintained in all the Flask applications.

    from flask import *;

     from  flask_mysqldb import MySQL

     import MySQLdb.cursors

     app=Flask(__name__)

 

 

 

 

    if __name__== '__main__' :

        app.run(debug=True)


after importing all the packages, have to mention some configured code for MySQL.

   app.config['MYSQL_HOST'] = 'localhost'

   app.config[ 'MYSQL_USER' ]  = 'root'

   app.config [ 'MYSQL_PASSWORD' ] =  ''

 

   app.config [ 'MYSQL_DB' ] = 'pyfile'

   mysql=MySQL(app)


after creating the structure and importing code, have to mention the Database host, username, password,Database name, if you didn't create a database, kindly check the previous site for how to crate a database by using python code. 

@app.route('/')

def home():

    return  render_template('index.html')


this is your first web application routing , if you give this route on your website, you will get what index.html file denoting, it will directly move to the page.

  @app.route('/store',methods=['GET','POST'])

  def store():

     

 

      if request.method=='POST' and 'ten' in request.form and 'name' in request.form and 'clg' in            request.form and 'op' in request.form:

        if request.form['op']=='insert':

            n=request.form['ten']

            n1=request.form['name']

            n2=request.form['clg']

 

            cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)

            cursor.execute("INSERT INTO sudha VALUES(%s,%s,%s)",(n,n1,n2));

            mysql.connection.commit()

            return "successfully inserted.....";

 

 

 

        elif request.form['op']=='delete':

          

            cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)

            n5=request.form['name']

            cursor.execute("DELETE FROM sudha WHERE name=%s",(n5,));

            mysql.connection.commit()

            return "deleted successfullyyy...";

 

        elif request.form['op']=="update":

            n6=request.form['ten']

            n7=request.form['name']

        

            cursor=mysql.connection.cursor(MySQLdb.cursors.DictCursor)

            cursor.execute("UPDATE sudha SET name=%s WHERE tennum=%s"  ,(n7,n6))

              mysql.connection.commit()

            return "updatedd sucessfully..."

        else:

            return "operations cant find..."

 


the above code indicates how to do the operation, if we click the route on your browser, it will give form i.e index.html and have to give the values on your foem, what kind of operation wanna proceeds, you just selected, based on the selection mode, it will the operation accordingly. 

whole code for this blog,

   from flask import *;

   from  flask_mysqldb import MySQL

   import MySQLdb.cursors

   app=Flask(__name__)

 

   app.config['MYSQL_HOST'] = 'localhost'

   app.config[ 'MYSQL_USER' ]  = 'root'

   app.config [ 'MYSQL_PASSWORD' ] =  ''

 

   app.config [ 'MYSQL_DB' ] = 'pyfile'

 

    mysql=MySQL(app)

   @app.route('/')

    def home():

      return  render_template('index.html')

    @app.route('/store',methods=['GET','POST'])

    def store():

     

 

      if request.method=='POST' and 'ten' in request.form and 'name' in request.form and 'clg' in               request.form and 'op' in request.form:

        if request.form['op']=='insert':

            n=request.form['ten']

            n1=request.form['name']

            n2=request.form['clg']

 

            cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)

            cursor.execute("INSERT INTO sudha VALUES(%s,%s,%s)",(n,n1,n2));

            mysql.connection.commit()

            return "successfully inserted.....";

 

 

 

        elif request.form['op']=='delete':

          

            cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)

            n5=request.form['name']

            cursor.execute("DELETE FROM sudha WHERE name=%s",(n5,));

            mysql.connection.commit()

            return "deleted successfullyyy...";

 

        elif request.form['op']=="update":

            n6=request.form['ten']

            n7=request.form['name']

        

            cursor=mysql.connection.cursor(MySQLdb.cursors.DictCursor)

            cursor.execute("UPDATE sudha SET name=%s WHERE tennum=%s"  ,(n7,n6))

            mysql.connection.commit()

            return "updatedd sucessfully..."

        else:

            return "operations cant find..."

 

 

 

    if __name__== '__main__' :

       app.run(debug=True)



you expected output looks like,









No comments:

Post a Comment