Quickflask: Flasking All The Things! and Then Some
Quickflask: Flasking All The Things! and Then Some
Quickflask: Flasking All The Things! and Then Some
@app.route("/")
@app.route("/index")
def index():
return "Hello Chadev Python Group!"
if __name__ == "__main__":
app.run()
{% block content %}
Hello Chadev Python user group!
{% endblock %}
Result:
Michael Scott Regional Manager
Dwight Schrute Assistant 'to the' Regional Manager
Jim Halpert Salesman
DRY templates with Jinja
Macros
//macros.html
{{% macro nav_link(endpoint, name) %}
{% if request.endpoint.endswith(endpoint) %}
<li class="active"><a href="{{ url_for(endpoint) }}">{{name}}</a></li>
{% else %}
<li><a href="{{ url_for(endpoint) }}">{{name}}</a></li>
{% endif %}
{% endmacro %}
Using Macros
//base.html
{% from "macros.html" import nav_link with context %}
..
<ul class="nav navbar-nav">
{{ nav_link('index', 'Home') }}
{{ nav_link('python', 'Python') }}
{{ nav_link('flask', 'Flask') }}
{{ nav_link('extensions', 'Extensions') }}
{{ nav_link('gifs', 'Gifs') }}
</ul>
update app.py
from flask import render_template
.
@app.route("/")
@app.route("/index")
def index():
return render_template('index.html')
More Jinja Awesomeness
Send a list to our template
//app.py
..
@app.route("/extns")
def extensions():
extns = ['Flask', 'Jinja2', 'Flask-SQLAlchemy', 'Flask-Admin',
'Flask-Classy', 'Flask-Raptor']
return render_template('extensions.html', extns=extns)
class SearchForm(Form):
query = StringField('query', validators=[DataRequired()])
Pull an image from giphy api
with python
import urllib, json
import random
..
def get_image(query):
url = 'http://api.giphy.com/v1/gifs/search?q='
api_key = 'dc6zaTOxFJmzC&limit=5'
data = json.loads(urllib.urlopen(url+query+'&api_key='+api_key).read())
item = random.choice(data['data'])
gif = item['images']['original']['url']
return gif
Send the image and form to
our template
from forms import SearchForm
app = Flask(__name__)
app.secret_key = 'some_secret_key'
..
@app.route("/gifs", methods=['GET', 'POST'])
def gifs():
form = SearchForm()
if form.validate_on_submit():
query = form.query.data
gif = get_image(query)
return render_template('gifs.html', gif=gif, form=form)
gif = 'static/img/dwight.gif'
return render_template('gifs.html', gif=gif, form=form)
gifs.html template
//gifs.html
{% extends "base.html" %}
{% block content %}
<form action="" method="post" name="query">
{{ form.hidden_tag() }}
<p>
Search for gifs:<br>
{{ form.query(size=20) }}<br>
{% for error in form.query.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}<br>
<input type="submit" value="Submit">
</p>
</form>