Flask

Some code comes from: http://flask.pocoo.org/docs/0.10/quickstart/
1.

  1. from flask import Flask
  2. app = Flask(__name__)
  3.  
  4. @app.route('/')
  5. def hello_world():
  6.     return 'Hello World!'
  7.  
  8. if __name__ == '__main__':
  9.     app.run()

2.
To let the server accessible for any other in the Network.

  1. app.run(host='0.0.0.0')

3.

  1. @app.route('/user/<username>')
  2. def show_user_profile(username):
  3.     # show the user profile for that user
  4.     return 'User %s' % username
  5.  
  6. @app.route('/post/<int:post_id>')
  7. def show_post(post_id):
  8.     # show the post with the given id, the id is an integer
  9.     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

4.

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

5.
Static Files

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

6.
request

  1. @app.route('/login', methods=['POST', 'GET'])
  2. def login():
  3.     error = None
  4.     if request.method == 'POST':
  5.         if valid_login(request.form['username'],
  6.                        request.form['password']):
  7.             return log_the_user_in(request.form['username'])
  8.         else:
  9.             error = 'Invalid username/password'
  10.     # the code below is executed if the request method
  11.     # was GET or the credentials were invalid
  12.     return render_template('login.html', error=error)

7.
request–>get

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

8.
Files Upload

  1. from flask import request
  2.  
  3. @app.route('/upload', methods=['GET', 'POST'])
  4. def upload_file():
  5.     if request.method == 'POST':
  6.         f = request.files['the_file']
  7.         f.save('/var/www/uploads/uploaded_file.txt')
  8.     ...

发布者

690130229

coder,喜欢安静,喜欢读书,wechat: leslie-liya

发表评论