343.Flask quickview

2017-08-20  本文已影响6人  科幻经典

New Run Model

export FLASK_APP=test.py
export FLASK_DEBUG=1
flask run

Variable Rule of URL

variable explain
float like int buf for floating point values
any matches one of the itmes provided

URL Building

@app.route('/login')
def login():pass

print(url_for('login', next='/')
/login?next=/

HTTP Methods

@app.route('/login', methods=['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']
the methods is attached to the route.

Static Files

To generate URLs for static files, use the special 'static' endpoint name:

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

Rendering Templates

To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:

from flask import render_template

@app.route('/')
@app.route('/<name>')

def hello(name=None):
    return render_template('hello.html', name=name)

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:

Case 1: a module:

/application.py
/templates
    /hello.html

Case 2: a package:

/application
    /__init__.py
    /templates
        /hello.html

Inside templates you also have access to the request, session and g [1] objects as well as the get_flashed_messages() function.

The most powerful part of Jinja is template inheritance. The {% extends %} tag is the key here. The extends tag must be the first tag in the template. To render the contents of a block defined in the parent template, use {{ super() }}.

Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer).

The Request Object

The current request method is available by using the method attribute. To access form data (data transmitted in a POST or PUT request) you can use the form attribute. Here is a full example of the two attributes mentioned above:

@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)

To access parameters submitted in the URL (?key=value) you can use the args attribute:

searchword = request.args.get('key', '')

File Uploads

You can handle uploaded files with Flask easily. Just make sure not to forget to set the enctype="multipart/form-data" attribute on your HTML form, otherwise the browser will not transmit your files at all.

So what does that secure_filename() function actually do? Now the problem is that there is that principle called “never trust user input”. This is also true for the filename of an uploaded file. All submitted form data can be forged, and filenames can be dangerous. For the moment just remember: always use that function to secure a filename before storing it directly on the filesystem.

filename = "../../../../home/username/.bashrc"

>>>secure_filename('../../../../home/username/.bashrc')
'home_username_.bashrc'
上一篇 下一篇

猜你喜欢

热点阅读