flask初探

一个最小的应用

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'hello world'

if __name__ == '__main__':
    app.run()

保存为hello.py,打开命令行输入:

python hello.py

然后浏览器访问:http://127.0.0.1:5000/,会看到 hello world。

调试模式

两个启用方法:

app.debug = True
app.run()
app.run(debug=True)

路由

在开始的应用中,route()把一个函数绑定到对应的URL上。

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'hello world'

变量规则

如果想要给URL添加变量,可以把这些特殊的字段标记为

@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_for() 来给指定的函数构造 URL。它接受函数名作为第一个参数,也接受对应 URL 规则的变量部分的命名参数。未知变量部分会添加到 URL 末尾作为查询参数。

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('index',username='John'))
/
/login
/login?next=/
/user/John%20Doe

login中是没有参数的,所以 next 是未知变量,用‘?’连接。

http方法

HTTP (与 Web 应用会话的协议)有许多不同的访问 URL 方法。默认情况下,路由只回应 GET 请求,但是通过 route() 装饰器传递 methods 参数可以改变这个行为。GET,POST通常通过html里的表单来提交。
比如html中创建一个表单:

<form action="/hello" method='post'>
    <input type="text" value="" name="val">
    <input type="submit" value="提交" id="submit">
</form>

点击提交键后,会向路由发起一个POST请求。在后端获取请求值,并打印出来。

@app.route('/hello', methods=['GET', 'POST'])
def show():
    if request.method == 'POST':
        val = request.form['val']
        return val
    else:
        return 'hello world'

静态文件

url_for('static', filename='style.css')

这个文件应该存储在文件系统上的 static/style.css。

模板渲染

Flask配备了Jinja2模板引擎,可以使用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)

hello.html里使用模板的一个小实例。

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello World!</h1>
{% endif %}

[1] http://docs.jinkan.org/docs/flask/quickstart.html#a-minimal-application flask中文文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值