欢迎访问我的博客~地平线上的一匹狼-Python flask (一)
第一节的代码
# -*- coding: utf-8 -*-
import sqlite3
from flask import Flask, request, session, g, redirect, url_for,abort, render_template, flash, jsonify
# configuration
DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
# create our little application :)
app = Flask(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
app.config['SECRET_KEY']='F34TF$($e34D';
@app.route('/_add_numbers')
def add_numbers():
a=request.args.get('a',0,type=int)
b=request.args.get('b',0,type=int)
return jsonify(result=a+b)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/signup',methods=['POST'])
def signup():
session['username']=request.form['username']
session['message']=request.form['message']
return redirect(url_for('message'))
@app.route('/message')
def message():
if not 'username' in session:
return abort(403)
return render_template('message.html',username=session['username'],message=session['message'])
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
if __name__ == '__main__':
app.run()
在这个例子中,用户将输入想要说的信息到第一个页面,即用户和,message,这些数据将被存储在session中并且将被同步显示在/message页面下.
Some observations:
- app.config
is a dict containing configuration parameters
- @app.route()
is by default limited to GET requests. Allowed HTTP methods of an action can be specified using the methods keyword arg.
- url_for(route_name, **kwargs)
should be used to generate urls for your handlers. It takes as first parameter the function name and as keyword args any needed parameters to generate the url.
- redirect(url)
creates an HTTP response with a redirect code and location
- abort(http_code)
is used to create error responses and stop the executing function.
Flask is natively integrated with jinja2
, a very good templating engine. Templates should be saved as .html files under the templates/ folder. The render_template(filename, **kwargs)
function is a pretty straightforward method to render them.
即render_template()函数接受任意多个参数,第一个参数是位于templates/下的模板文件,之后的参数均是模板文件内定义的数据.
然后我们使用jinja渲染html.代码如下
index.html:
{% extends "layout.html" %}
{% block content %}
<h1>Say something</h1>
<form method="post" action="{{ url_for('signup') }}">
<p><label>Username:</label> <input type="text" name="username" required></p>
<p><label>Message:</label> <textarea name="message"></textarea></p>
<p><button type="submit">Send</button></p>
</form>
{% endblock %}
message.html:
{% extends "layout.html" %}
{% block content %}
<h1>{{ username }} said:</h1>
<p>
{{ message }}
</p>
<a href="{{ url_for('home') }}">Say something else</a>
{% endblock %}
layout.html:
<!doctype html>
<html lang="en">
<head>
<title>Say somthing</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
其中,模板中的url_for()是从 static/ 目录下get到当时路由定义函数渲染的页面.比如这里会转到index.html