start Flask and create a simple project Supporting tagline
Part One : install flask and make it work on laptop.
step 1.install falsk on mac
sudo easy_install virtualenv
or
sudo pip install virtualenv
virtualenv can separate different python projects from its Environment.
step 2.cerate environment:
mkdir myproject
cd myproject
virtualenv env
then it would come the information below.
“New python executable in env/bin/python”
“Installing setuptools…………done.”
step 3.active its environment:
. env/bin/activate
take care about the dot and the space ,if this command can not be used , try to use source
step 4.active Flask in your virtualenv:
easy_install Flask
Part Two : Start Flask project.
step 5.write a file named “hello.py”,with code below :
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run()
Then run python hello.py
,we can see “Hello World!” in http://127.0.0.1:5000/
how it works?
import Flask
tell us to create a WSGI program.
then route
tell us which page will trigger this function hello_world()
we use app.run()
to run the local server , Ctrl+C
to stop.
if we want to interview this project from outside, use app.run(host='0.0.0.0')
Some details:
details 1 : add app.debug = True
,it will let us to debug the project from server . but please remember,
we can not use app.debug = True
under Production, cause this allow user to run his code in Production.
details 2 : we can use variable to set the RUL
@app.route('/user/<username>')
def show_user_profile(username):
return username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return post_id
we can use int
,float
,path
to limit the type of input.
details 3 : HTTP methods
in route(), we can add methods= ['get','post']
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()
details 4 : static files
create a folder /static , js or CSS can be stored here,if style.css under this folder,use url_for('static', filename='style.css')
to interview this file.
details 5 : template
Flask use Jinja2 as render_templates, use render_template()
to render templates,put the pages under templates
.
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
then Flask will find “hello.html” under templates
details 6 : files upload
remember set enctype="multipart/form-data"
in the html form.
it will create a request object with its attribute file
,and use save()
to save.
and please never believe its “file_name” ,this name will be faked easily. so use secure_filename()
to make it safe .
from flask import request
from werkzeug import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/' + secure_filename(f.filename))
... ...
details 7 : redirect and ERROR
if we want to jump to another URL, use redirect()
; if we want to interrupt a request and return flase info, use abort()
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
details 8 : log
there is a class Logger,use like this :
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
Part Three : create a project by flask
the project is here
then we start it step by step.
one : create folders for this project
create /static
and /templates
under /flaskr
. “static” is for user request, also we put CSS and JS here;”templates” for rendering templates, all the templates will be put here.
two : deploy
in order to create db information, create “schema.sql”, Click here.
three : create a main module
create a file named “flaskr.py”, and add
# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash
# configuration
DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
username is “admin” and password is “default”.
then create app, in the same py file
# create our application
app = Flask(__name__)
app.config.from_object(__name__)
of course , we need to link to the db, so also add
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
at last , start server with
if __name__ == '__main__':
app.run()
four : create db for app and link
create db by
sqlite3 /tmp/flaskr.db < schema.sql
then link by
@app.before_request
def before_request():
g.db = connect_db()
@app.after_request
def after_request(response):
g.db.close()
return response
“@app.before_request” can be called before rquest, and “@app.after_request” can be call after request.
five : view functions
we need functions to show the views. here’s the functions we want.
“show_entries()” for ”/”, to show index.
“add_entry()” for “/add”, to add new archives.
“login()” for “/login”, for user to login in .
“logout()” for “/logout”, for user to logout.
so all the code is here.
six : add templates.
templates inculdes “layout.html”,”show_entries.html”,”login.html”
please check here.
seven : add CSS
add “style.css” under “static” , check here .
eight : start server
at last, start server with “python flaskr.py”.
blog comments powered by Disqus