0 likes | 22 Views
Learn about Flask, a microframework for Python that simplifies web development by taking care of repetitive tasks, allowing you to focus on unique project features. This outline covers setting up directory structure, creating a virtual environment, testing your first Flask application, and working with templates, dynamic behavior, URL routing, and web forms.
E N D
Flask CS373 –Software Engineering
Outline What is Flask? Before you start Creating and Testing your First Flask application Flask application with a template Flask application with dynamic behavior Flask application with “url_for” Passing arguments to Flask templates Flask application with web forms
What is Flask? Flask is a microframework for Python Microframes are collections of code that simplify the web development process They take care of repetitive tasks and allows us to focus on the more unique features of your project
Before you Start Set up the directory structure Create a virtual environment
Set up the Directory Structure A web application typically has a directory for templates and • a directory for static contents • A Flask application will look for html documents in the templates folder Create the folder "cs373-idb“, switch inside it and create the two subfolders “templates” and “static” : $ mkdir cs373-idb $ cd cs373-idb $ pwd /c/Users/fares/Documents/cs373-idb $ mkdir templates $ mkdir static
Set up the Directory Structure Switch inside the folder “static” and create the subfolders “css”, “images”, and “js” $ cd static $ pwd /c/Users/fares/Documents/cs373-idb/static $ mkdir css $ mkdir images $ mkdir js Switch back to the root folder "cs373-idb" $ cd .. $ pwd /c/Users/fares/Documents/cs373-idb
Before you Start Set up the directory structure Create a virtual environment
Virtual Environment This allows you to have a Python distribution specifically for your project, so you can install only the packages you need. Create a virtual environment Activate the virtual environment “venv” Install basic modules
Create a Virtual Environment Create a virtual environment (Note: you may need first to install virtualenv : “pip install virtualenv” ) Make sure you are inside the folder “cscs373-idb” and create a virtual environment “venv” On Windows: $ virtualenv venv On Mac: $ pyvenv venv On linux: $ virtualenv -p python3 venv
Virtual Environment Create a virtual environment Activate the virtual environment “venv” Install basic modules
Activate the Virtual Environment On Windows (assuming you’re using Git Bash): $ . venv/Scripts/activate (venv) $ On Mac: $ source venv/bin/activate (venv) $ On linux: $. venv/bin/activate (venv) $
Create a Virtual Environment Create a virtual environment Activate the virtual environment “venv” Install basic modules
Install Basic Modules On Windows, Mac and Linux: # install flask in your venv: (venv) $ pip install flask # install Flask-SQLAlchmey (needed for the next project): (venv) $ pip install Flask-SQLAlchemy Note: We will use PostgreSQL database. With Flask it's common to use an object relational mapper (ORM) to access the database. This allows you to query a database using classes and methods rather than writing raw SQL. SQLAlchemy is a popular ORM for python and there's a wrapper version for Flask specifically (Flask-SQLAlchemy).
Install Basic Modules # Install psycopg2 in venv (needed later on). # Note: you need to install PostgreSQL first to be able to install psycopg2 (venv) $ pip install psycopg2-binary Note: psycopg2 is an adapter that allows Python applications to communicate with a PostgreSQL database. (3) Deactivate virtual environment (venv) $ deactivate
Creating your First Flask Application make sure that you are on the root of your director structure, i.e., "cs373-idb", # main.py (v1.0) from flask import Flask open your editor, app = Flask(__name__) type in the commands in the slide to the side, @app.route('/') and save to a file, "main.py". def index(): return "Hello World" if __name__ == "__main__": app.run()
Testing your First Flask Application At the root of your project folder type the following (make sure your environment is activated!) (venv) $ python main.py You will see an output that may look like the following: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) To see the output of your main.py, go to your internet browser, navigate to "http://127.0.0.1:5000/" and you should be presented with "Hello World" Alternatively, you can navigate to "http://localhost:5000"
Flask Application with a Template We will modify our “main.py” to print "Hello World" by rendering a template. We need to import "render_template" in order to be able to use templates. We need to create an html file, "hello.html", and save it inside the directory "template". In “main.py”, replace “return “Hello World!” with “return render_template('hello.html')”
Flask Application with a Template <!– index.html --> <html> <head></head> <body> <p>Hello World</p> </body> </html> # main.py (v2.0) from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run()
Flask Application with Dynamic Behavior # main.py (v3.0) <!– book.html --> <html> <head> </head> <body> <p>The index of the book is {{ id }}</p> </body> </html> from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/book/<int:id>/') def book(id): return render_template('book.html', id = id) if __name__ == "__main__": app.run()
Flask Application with ‘url_for’ <!– book.html --> <html> <head> </head> <body> <p>The index of the book is {{ id }}</p> <a href="{{url_for('index')}}"> Main Menu</a><br/> </body> </html> # main.py (v4.0) from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/book/<int:id>/') def book(id): return render_template('book.html', id = id) if __name__ == "__main__": app.run()
Passing Arguments to Flask templates # main.py (v5.0) from flask import Flask, render_template app = Flask(__name__) books = [{'title': 'Software Engineering', 'id': '1'}, \ {'title':'Algorithm Design', 'id':'2'}, \ {'title':'Python', 'id':'3'}] @app.route('/') def index(): return render_template('index.html') @app.route('/book/') def book(): return render_template('book.html', books = books) if __name__ == "__main__": app.run()
Passing Arguments to Flask templates <!– book.html --> <html> <head></head> <body> <p>This is the books page</b> <a href="{{url_for('index')}}">Main Menu</a> <br/> <h1>Books</h1> {% if books == [] %} <p>No books exist</p> {% else %} {% for i in books %} <div> {{i.title}} <br/> <br/> </div> {% endfor %} {% endif %} </body> </html>
Flask Application with Web Forms A web forms is a way for a user to provide information. The user fills a form and presses submit button, the browser send a special request to the server. In the previous requests, aka GET requests, the browser asks the server for contents. In web forms requests, the browser sends contents to the server, aka POST requests.
Flask Application with Web Forms <!– index.html --> <html> <head> </head> <body> <p>Hello World</p> Search: <form action="{{url_for('bookSearch')}}" method = 'POST'> <input type='text' size='30' name='name'> <input type='submit' value='Submit'> </form> </body> </html>
Flask Application with Web Forms # main.py (v6.0) @app.route('/search/', methods=['GET','POST']) def bookSearch(): if request.method == 'POST': search_key = request.form['name'] return redirect(url_for('manyBooks', nm = search_key)) else: # if my server didn't receive a POST request, it's going to # redirect the user back to the main index page. # The helper function 'redirect' is used to accomplish that. return render_template('index.html')
Flask Application Responds with JSON # main.py (v7.0) @app.route('/book/json/') def bookjson(): r = json.dumps(books) return Response(r)
References: For more information about Flask, you can visit : https://flask.palletsprojects.com/en/1.0.x/tutorial/factory/ For more information about “Jinja template engine”, you can visit: http://jinja.pocoo.org/ https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/Pyth on3_Flask.html