Created
August 6, 2019 10:11
-
-
Save gtindo/21ff6b6ec4ddf7350291a877607c157a to your computer and use it in GitHub Desktop.
Flask quick start
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, escape, url_for, request, redirect, session | |
from werkzeug.utils import secure_filename | |
#Instancier une application Flask | |
app = Flask(__name__) | |
# Set the secret key to some random bytes. Keep this really secret! | |
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' | |
########################## | |
# Creer des route # | |
########################## | |
@app.route('/') | |
def hello_world(): | |
return 'Hello, World!' | |
@app.route('/hello') | |
def hello(): | |
return 'Hello, world 2' | |
#route with string param | |
@app.route('/user/<username>') | |
def show_user_profile(username): | |
return 'User {}'.format(username) | |
#route with integer param | |
@app.route('/post/<int:post_id>') | |
def show_post(post_id): | |
return 'Post %d' % post_id | |
#route with path param | |
@app.route('/path/<path:subpath>') | |
def show_subpath(subpath): | |
return 'Subpath {}'.format(subpath) | |
@app.route('/utilisateur/<username>') | |
def profile(username): | |
return '{}\'s profile'.format(escape(username)) | |
#get the url of a fuction or a static file | |
with app.test_request_context(): | |
print(url_for('profile', username="John")) | |
print(url_for('show_post', post_id=1)) | |
print(url_for('show_subpath', subpath="home")) | |
print(url_for('static', filename='style.css')) | |
#Can be usefull for unit testing | |
with app.test_request_context('/hello', method='POST'): | |
assert request.path == '/hello' | |
assert request.method == 'POST' | |
#Other way to make a test | |
with app.request_context(environ): | |
assert request.method == 'POST' | |
#Handle multiple request type with a function | |
@app.route('/login', methods=['GET', 'POST']) | |
def login(): | |
if request.method == 'POST': | |
return do_the_login() | |
else: | |
return show_the_login_form() | |
#Randering template with flask, jinja2 work like django template | |
@app.route('/home/<string:name>') | |
def home(name): | |
return render_template('home.html', name=name) | |
#Request object in details | |
@app.route('/login_2', 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' | |
return render_template('login.html', error=error) | |
#get params of a request | |
@app.route('/params', methods=['GET']) | |
def params(): | |
try: | |
searchword = request.args.get('key', '') | |
except KeyError: | |
return 'Bad key provided' | |
return searchword | |
#handle File Upload with flask | |
@app.route('/upload', methods=['GET', 'POST']) | |
def upload_file(): | |
if request.method == 'POST': | |
f = request.files['the_file'] | |
f.save('/var/www/uploads/' + secure_filename(f.filename)) | |
#make redirectios | |
@app.route('/') | |
def index(): | |
return redirect(url_for('login')) | |
#raise http errors | |
def login(): | |
abort(401) | |
this_is_never_executed() | |
#Customize errors pages | |
@app.errorhandler(404) | |
def page_not_found(error): | |
return render_template('page_not_found.html'), 404 | |
#Returning JSON With dict object | |
@app.route("/me") | |
def me_api(): | |
user = get_current_user() | |
return { | |
"username": user.name, | |
"theme": user.theme, | |
"image": url_for("user_image", filename=user.image) | |
} | |
#Returning JSON with jsonify() function | |
@app.route("/users_api") | |
def users_api(): | |
users = get_all_users() | |
return jsonify([user.to_json() for user in users]) | |
#Manage sessions | |
@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 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')) | |
#Logging | |
app.logger.debug('A value for debugging') | |
app.logger.warning('A warning occurred (%d apples)', 42) | |
app.logger.error('An error occurred') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment