我们可以使用Python语言快速实现一个网站或Web服务。本文参考自Flask官方文档,大部分代码引用自官方文档。
首先我们来安装Flask。最简单的办法就是使用pip,当你装好了python后,直接在命令行下输入。
pip install flask
然后打开一个文件,输入下面的内容并保存为app.py,然后在命令行下换到文件所在目录,再(python app.py)运行该文件。然后浏览器访问IP:5000,我们应当可以看到浏览器上输出了hello world。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000)
路径变量
如果希望获取/article/1这样的路径参数,就需要使用路径变量。路径变量的语法是/path/<converter:varname>。在路径变量前还可以使用可选的转换器,有以下几种转换器。
| 转换器 | 作用 |
|---|---|
| string | 默认选项,接受除了斜杠之外的字符串 |
| int | 接受整数 |
| float | 接受浮点数 |
| path | 和string类似,不过可以接受带斜杠的字符串 |
| any | 匹配任何一种转换器 |
| uuid | 接受UUID字符串 |
下面是Flask官方的例子。
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
构造URL
通过构建URL的方式直接在代码中拼URL的原因有两点:
1.将来如果修改了URL,但没有修改该URL对应的函数名,就不用到处去替换URL了。
2. url_for()函数会转义一些特殊字符和unicode字符串,这些事情url_for会自动的帮助我们搞定。
在Web程序中常常需要获取某个页面的URL,在Flask中需要使用url_for('方法名')来构造对应方法的URL。下面是Flask官方的例子。
>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> @app.route('/')
... def index(): pass
...
>>> @app.route('/login')
... def login(): pass
...
>>> @app.route('/user/<username>')
... def profile(username): pass
...
>>> with app.test_request_context():
... print url_for('index')
... print url_for('login')
... print url_for('login', next='/')
... print url_for('profile', username='John Doe')
...
/
/login
/login?next=/
/user/John%20Doe
HTTP方法
如果需要处理具体的HTTP方法,在Flask中也很容易,使用route装饰器的methods参数设置即可。
get和post 请求区别:
get是将请求写在url里的。
而post是写在form表单中的。
在route的methods中,写好post方法,否则默认是get,一旦请求方式是post会报错。
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()
静态文件
Web程序中常常需要处理静态文件,在Flask中需要使用url_for函数并指定static端点名和文件名。在下面的例子中,实际的文件应放在static/文件夹下。
url_for('static', filename='style.css')
模板生成
Flask默认使用Jinja2作为模板,Flask会自动配置Jinja 模板,所以我们不需要其他配置了。默认情况下,模板文件需要放在templates文件夹下。
使用 Jinja 模板,只需要在python文件中使用render_template函数并传入模板文件名和参数名即可。
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
相应的templates文件夹里的HTML模板文件如下。用两个大括号写变量,用大括号加百分号写语句,访问时输入IP:端口/hello/就可以访问
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}