Flask - The Basics


/ Published in: Python
Save to your folder(s)

Snippet showing a simple Flask application to illustrate the topics covered in the "Quickstart".


Copy this code and paste it in your HTML
  1. from flask import Flask, url_for, request, render_template, flash, redirect, abort, session, escape
  2. app = Flask(__name__)
  3.  
  4. # setting the secret_key generate with: >>> import os; os.urandom(24)
  5. app.secret_key = '\x1eo\xc0\xd84\x8c\xfez\xbc\x0eQ\xc2\xb4we\xa8p\r\x13\\\x88\x97\x8e\xb9'
  6.  
  7. # route() decorator is used to bind a function to a URL
  8. @app.route('/')
  9. def index():
  10. return '<b>Index Page</b>'
  11.  
  12. @app.route('/hello')
  13. def helloWorld():
  14. return '<b>Hello World!</b>'
  15.  
  16. # route() accepts URLs with variable parts
  17. @app.route('/hello/<user>')
  18. def helloUser(user):
  19. return '<b>Hello %s!</b>' % user
  20.  
  21. # rules may also be specified using a converter. Converter types:
  22. # int accepts integers
  23. # float like int but for floating point values
  24. # path like the default but also accepts slashes
  25. @app.route('/hello/<user>/<int:greetingsCount>')
  26. def helloUserN(user, greetingsCount):
  27. greetingsCount = abs(greetingsCount)
  28. if greetingsCount > 3:
  29. app.logger.warning('Warning! The greetings count %d is above the limit (3).', greetingsCount)
  30. returnValue = ''
  31. while greetingsCount > 0:
  32. returnValue += '<b>Hello %s!</b><br />' % user
  33. greetingsCount -= 1;
  34. return returnValue
  35.  
  36. # building URLs using the url_for() function. Unknows variables are appended to the URL as query parameters
  37. @app.route('/urls')
  38. def printUrls():
  39. builtUrls = ''
  40. builtUrls += url_for('index') + '<br />'
  41. builtUrls += url_for('helloWorld') + '<br />'
  42. builtUrls += url_for('helloWorld', user='user') + '<br />'
  43. builtUrls += url_for('helloUser', user='user') + '<br />'
  44. builtUrls += url_for('helloUserN', user='user', greetingsCount='3') + '<br />'
  45. return builtUrls
  46.  
  47. # example on how to access the request object
  48. # To access parameters submitted in the URL (?key=value) you can use the args attribute:
  49. # searchword = request.args.get('key', '')
  50. # by default, a route only answers to GET requests, but it can be changed, as below:
  51. @app.route('/login', methods=['GET', 'POST'])
  52. def login():
  53. if request.method == 'POST':
  54. if isCredentialsValid(request.form['username'], request.form['password']):
  55. # escape() used here does escaping for you. Can be used when you are not using the template engine
  56. session['username'] = escape(request.form['username'])
  57. return redirect(url_for('ghibliIndex'))
  58. else:
  59. app.logger.error('Invalid username and/or password provided.')
  60. flash('Invalid username and/or password.', 'error')
  61.  
  62. # the code below this is executed if the request method
  63. # was GET or the credentials were invalid
  64. return render_template('login.html')
  65.  
  66. def isCredentialsValid(username, password):
  67. if username == 'user' and password == 'pass':
  68. return True
  69. return False
  70.  
  71. @app.route('/logout')
  72. def logout():
  73. # remove the username from the session if it's there
  74. session.pop('username', None)
  75. return redirect(url_for('ghibliIndex'))
  76.  
  77. # example of how to deal with templates
  78. @app.route('/ghibli')
  79. @app.route('/ghibli/<name>')
  80. def ghibliIndex(name=None):
  81. return render_template('ghibli.html', name=name, ghibliLogoUrl=url_for('static', filename='ghibli.gif'))
  82.  
  83. # example of how to deal with templates
  84. @app.route('/upload', methods=['GET', 'POST'])
  85. def upload():
  86. if request.method == 'POST':
  87. f = request.files['filename'];
  88.  
  89. # to save the file, the line below could be used
  90. # f.save('/var/www/uploads/uploaded_file.txt')
  91.  
  92. # f.filename contains the name of the file on the client, before it was uploaded,
  93. # but it should not be trusted. If it is wanted to use it, pass it though the
  94. # secure_filename function
  95. # from werkzeug import secure_filename
  96. # f.save('/var/www/uploads/' + secure_filename(f.filename))
  97.  
  98. flash('Content of the uploaded file:', 'message')
  99.  
  100. messages = []
  101. lines = f.readlines()
  102. for line in lines:
  103. flash(line, 'message')
  104.  
  105. # example of how to use the redirect() function to guide use to an endpoint
  106. return redirect(url_for('upload'))
  107. return render_template('upload.html')
  108.  
  109. # useless route to illustrate the usage of abort() function
  110. @app.route('/forbidden')
  111. def forbidden():
  112. abort(401)
  113.  
  114. @app.errorhandler(404)
  115. def page_not_found(error):
  116. app.logger.debug('Reached page not found handler.')
  117. return render_template('page_not_found.html', makkuroUrl=url_for('static', filename='makkuro.jpg')), 404
  118.  
  119. # this function could be written using the make_response() function
  120. # resp = make_response(render_template('page_not_found.html', makkuroUrl=url_for('static', filename='makkuro.jpg')), 404)
  121. # resp.headers['X-Something'] = 'A value'
  122. # return resp
  123.  
  124. if __name__ == '__main__':
  125. # app.run()
  126.  
  127. # Enabling debug mode - NEVER USE IT IN PRODUCTION
  128. # Almost mandatory in development environments because, if enabled, the server will
  129. # reload itself on code changes
  130. app.run(debug=True)
  131. # or
  132. # app.debug = True
  133. # app.run()
  134.  
  135. # Making the built-in server externally visible
  136. # It is disabled by default because in debugging mode a user of the application
  137. # can execute arbitrary Python code on the machine
  138. # Enable it if debug is disabled or users on the network can be trusted
  139. # app.run(host='0.0.0.0')

URL: http://flask.pocoo.org/docs/quickstart/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.