chenxiaba / mywork

记录平时的笔记
0 stars 0 forks source link

flask #16

Open chenxiaba opened 8 years ago

chenxiaba commented 8 years ago

相关库: Successfully installed flask Werkzeug Jinja2 itsdangerous MarkupSafe

chenxiaba commented 8 years ago

网址: http://flask.pocoo.org/

SQLAlchemy http://www.sqlalchemy.org/

The main goal of SQLAlchemy is to change the way you think about databases and SQL!

RESTFUL API: http://www.pythondoc.com/flask-restful/first.html

chenxiaba commented 8 years ago

http://flask.pocoo.org/docs/0.10/quickstart/#quickstart

chenxiaba commented 8 years ago

演示项目: https://github.com/mitsuhiko/flask/blob/master/examples/minitwit/minitwit.py

chenxiaba commented 8 years ago

使用变量:

@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

The following converters exist: int accepts integers float like int but for floating point values path like the default but also accepts slashes

chenxiaba commented 8 years ago

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

url_for('static', filename='style.css')
chenxiaba commented 8 years ago

Rendering Templates:

from flask import render_template

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

Jinjia2: http://jinja.pocoo.org/docs/dev/templates/

chenxiaba commented 8 years ago

API: http://flask.pocoo.org/docs/0.10/api/#flask.request

chenxiaba commented 8 years ago

Message Flashing: http://flask.pocoo.org/docs/0.10/patterns/flashing/#message-flashing-pattern

chenxiaba commented 8 years ago

使用日志:

app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
chenxiaba commented 8 years ago

使用session:

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 '''
        <form action="" method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

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

生成key:

>>> import os
>>> os.urandom(24)
chenxiaba commented 8 years ago

异常处理:

@app.errorhandler(404)
def not_found(error):
    return render_template('error.html'), 404

一般对于form里的异常,一般不用try/catch,对于url里的异常,建议使用try/catch,由于用户修改url是很平常的

chenxiaba commented 8 years ago

make response:

@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('error.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp
chenxiaba commented 8 years ago

redirect、abort:

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()
chenxiaba commented 8 years ago

Cookies
reading cookies:

from flask import request

@app.route('/')
def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.

storing cookies:

from flask import make_response

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

Request:

@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)
chenxiaba commented 8 years ago

Rendering Templates:

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 %}

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

chenxiaba commented 8 years ago

Static Files:

url_for('static', filename='style.css')
chenxiaba commented 8 years ago

HTTP methods:

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

test_request_context:

>>> 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
chenxiaba commented 8 years ago

Foreword for Experienced Programmers http://flask.pocoo.org/docs/0.10/advanced_foreword/#advanced-foreword

Thread-Locals in Flask

One of the design decisions in Flask was that simple tasks should be simple; they should not take a lot of code and yet they should not limit you. For example, Flask uses thread-local objects internally so that you don’t have to pass objects around from function to function within a request in order to stay threadsafe.

Develop for the Web with Caution

Always keep security in mind when building web applications.

If you write a web application, you are probably allowing users to register and leave their data on your server. The users are entrusting you with data. And even if you are the only user that might leave data in your application, you still want that data to be stored securely.

chenxiaba commented 8 years ago

Tutorial: http://flask.pocoo.org/docs/0.10/tutorial/

chenxiaba commented 8 years ago

RSET API:

#==========  ===============================================  =============================
#HTTP 方法     URL                                                             动作
#==========  ===============================================  ==============================
#GET             http://[hostname]/todo/api/v1.0/tasks                       检索任务列表
#GET             http://[hostname]/todo/api/v1.0/tasks/[task_id]             检索某个任务
#POST            http://[hostname]/todo/api/v1.0/tasks                       创建新任务
#PUT             http://[hostname]/todo/api/v1.0/tasks/[task_id]             更新任务
#DELETE          http://[hostname]/todo/api/v1.0/tasks/[task_id]             删除任务
#==========  ================================================ =============================