flask快速入门

第一个flask程序

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.debug = True #调试模式
    app.run()

url变量

在url中的路径可以当做变量传到相应的处理函数里面

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

url里面的函数还可以经过转换
@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

可转换的内容如下

int 接受整数
float 同 int ,但是接受浮点数
path 和默认的相似,但也接受斜线

关联url

@app.route('/projects/')
def projects():
    return 'The project page'
这种url如果访问了不带/结尾的 那么会被flask重定向到带/的规范url里面

@app.route('/about')
def about():
    return 'The about page'
如果访问了带/结尾的url  会404

构造 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')  #根据函数来生成由他处理的url
...  print url_for('login')
...  print url_for('login', next='/')
...  print url_for('profile', username='John Doe')
...
/
/login
/login?next=/
/user/John%20Doe

HTTP 方法

默认情况下 route只响应get请求

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
       do_the_login()
    else:
        show_the_login_form()

静态文件

需要提供静态文件的地方
只要在你的包中或是模块的所在目录中创建一个名为 static 的文件夹,在应用中使用 /static 即可访问。

给静态文件生成 URL ,使用特殊的 ‘static’ 端点名:

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

模板渲染

使用 render_template() 方法来渲染模板.
Flask 会在 templates 文件夹里寻找模板。所以,如果你的应用是个模块,这个文件夹应该与模块同级;如果它是一个包,那么这个文件夹作为包的子目录:

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

访问请求数据

Flask 中由全局的 request 对象来提供这些信息.

request.method 获得请求方式
request.form获得post 的参数
如果获取的参数没有那么默认返回400 badrequest..然后还会产生异常会抛出一个特殊的 KeyError 异常。

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)

文件上传

上传的问在存储在
request对象的files对象里面

获得cookie
request 对象的cookies.get(‘name’)

设置cookie

from flask import make_response

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

重定向和错误

redirect() 函数把用户重定向到其它地方
“`
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()


定制错误页面

errorhandler() 装饰器:

from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
return render_template(‘page_not_found.html’), 404

##关于响应
如果返回值是一个字符串, 它被转换为该字符串为主体的、状态码为 200 OK``的 、 MIME 类型是 ``text/html 的响应对象

Flask 把返回值转换为响应对象的逻辑是这样:

如果返回的是一个合法的响应对象,它会从视图直接返回。
如果返回的是一个字符串,响应对象会用字符串数据和默认参数创建。
如果返回的是一个元组,且元组中的元素可以提供额外的信息。这样的元组必须是 (response, status, headers) 的形式,且至少包含一个元素。 status 值会覆盖状态代码, headers 可以是一个列表或字典,作为额外的消息标头值。
如果上述条件均不满足, Flask 会假设返回值是一个合法的 WSGI 应用程序,并转换为一个请求对象。

#session
如果想使用session必须要先设置secret_key

from flask import Flask, session, redirect, url_for, escape, request

app = Flask(name)

@app.route(‘/’)
def index():
if ‘username’ in session:
return ‘Logged in as %s’ % escape(session[‘username’])
return ‘You are not logged in’

@app.route(‘/login’, methods=[‘GET’, ‘POST’])
def login():
if request.method == ‘POST’:
session[‘username’] = request.form[‘username’]
return redirect(url_for(‘index’))
return ”’




”’

@app.route(‘/logout’)
def logout():
# remove the username from the session if it’s there
session.pop(‘username’, None)
return redirect(url_for(‘index’))

set the secret key. keep this really secret:

app.secret_key = ‘A0Zr98j/3yX R~XHH!jmN]LWX/,?RT’
“`

消息闪现

要和模板配合 .提供消息闪现
flash() 方法可以闪现一条消息。要操作消息本身,请使用 get_flashed_messages() 函数

日志记录

app.logger.debug(‘A value for debugging’)
app.logger.warning(‘A warning occurred (%d apples)’, 42)
app.logger.error(‘An error occurred’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值