Introduction to Flask
Flask is the minimalistic simple Web Framework for Python. Want to start serving page immediately ?
Save the following
Navigate to http://localhost:5000/ and you will get the Hello World message.
Flask comes with the Werkzeug server and Jinja2 templating which both of them done by Armin Ronacher.
Templating
Create a folder named templates and lets add a basic HTML page under the templates folder.
How to send a parameter to Flask template ?
Adding our parameter to the hello.html
As you see, {{name}} added to our HTML file. All we need to do, add name as a named parameter to our render_template
How to serve static files from Flask ?
Our previous code was
We would like to serve our static files in our development environment. Let's create a static folder under our project to put JavaScript, CSS, Images
Set use_reloader=True to restart flask server whenever a Python file changes. Very handy!
Flask is the minimalistic simple Web Framework for Python. Want to start serving page immediately ?
Kod:
mkdir flask101 cd flask101 virtualenv venv source venv/bin/activate pip install Flask vim server.py
Kod:
from flask import Flask app = Flask(__name__) @[URL="https://www.turkhackteam.org/member.php?u=437476"]app[/URL].route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run()
bash python server.py
Flask comes with the Werkzeug server and Jinja2 templating which both of them done by Armin Ronacher.
Templating
Create a folder named templates and lets add a basic HTML page under the templates folder.
Kod:
<!DOCTYPE html> <html> <body> Hello world from flask </body> </html>
Kod:
from flask import Flask, render_template import os # if you have different folder path than templates, uncomment the following lines... # current_dir = os.path.dirname(os.path.abspath(__file__)) # template_folder = os.path.join(current_dir, 'templates') app = Flask(__name__) #, template_folder=template_folder) @[URL="https://www.turkhackteam.org/member.php?u=437476"]app[/URL].route("/") def hello(): #return "Hello World!" return render_template("hello.html") if __name__ == "__main__": app.run(debug=True)
How to send a parameter to Flask template ?
Adding our parameter to the hello.html
Kod:
<!DOCTYPE html> <html> <body> Hello world from flask! My name is {{name}} </body> </html>
Kod:
@[URL="https://www.turkhackteam.org/member.php?u=437476"]app[/URL].route("/") def hello(): #return "Hello World!" return render_template("hello.html", name='Ozgur')
How to serve static files from Flask ?
Our previous code was
Kod:
if __name__ == "__main__": app.run(debug=True)
Kod:
mkdir static && cd static mkdir img && mkdir js && mkdir css
from werkzeug import SharedDataMiddleware if __name__ == "__main__": if app.debug: app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/static': static_folder }) app.run(debug=True, use_debugger=True, use_reloader=True)
Son düzenleme: