QuickFlask Flasking all the things! And then some Created by /Justin Spain @jwsmusic
What is Flask? A MicroFramework written in Python for the web Micro meaning simple core but highly extensible Used to create websites and api's
Other Python Frameworks Django Bottle CherryPy Pecan Pyramid web.py ...
Why Flask Easy to learn Small but can easily handle large apps Awesome documentation * Written in Python Routes by decorators Import only what you need Pythonic New plugins every day Flask-Migrate using Alembic Vast array of extensions
Flask VS. Django Django - batteries included: Can be overkill for small projects Built-in template engine, ORM, and Admin Steeper learning curve Flask - one drop at a time Install what you need, when you need it Can add complexity as needed Install different template engine, ORM, and Admin easily Easy to learn
My Development Environment Xubuntu 14.04 Python 2.7.6 Virtualenv - creates isolated Python environments Pip - installs & manages Python packages
Project Structure mkdirQuick-Flask cdQuick-Flask mkdirChadevPython mkdirChadevPython/static mkdirChadevPython/templates touchREADME.md touchChadevPython/app.py //makeprojecteasilyexecutable chmod+xChadevPython/app.py
Create and activate virtual environment virtualenvenv .env/bin/activate
Do the Flask Install Dance!!! pipinstallFlask
At terminal run project ./app.py Open http://localhost:5000 Add code to app.py #!/usr/bin/envpython fromflaskimportFlask app=Flask(__name__) @app.route("/") @app.route("/index") defindex(): return"HelloChadevPythonGroup!" if__name__=="__main__": app.run()
Done You can write Flask apps now!
Add another route @app.route("/python") defpython(): return"Pythonallthethings!"
At terminal run project ./app.py Open http://localhost:5000 Return simple html @app.route("/flask") defflask(): return"<h1>Flaskalltheweb!</h1>"
Jinja awesomness with templates Add code to base.html and index.html //base.html <divclass="container"> <h2>ChadevPythonusergroup!</h2> <ahref="{{url_for('index')}}">Home|</a> <ahref="{{url_for('python')}}">Python|</a> <ahref="{{url_for('flask')}}">Flask|</a> <ahref="{{url_for('extensions')}}">Extensions</a> <br><br><br> {%blockcontent%}{%endblock%} <br><br><br><br> <h2>LearningFlaskthings</h2> </div> Syntax for pulling in a variable from Flask {{some_variable}}
Jinja awesomness with templates Extending base.html and putting content inside a block //index.html {%extends"base.html"%} {%blockcontent%} HelloChadevPythonusergroup! {%endblock%} Syntax to add logic to templates {%for%} {%endfor%}
Michael Scott Regional Manager Dwight Schrute Assistant 'to the' Regional Manager Jim Halpert Salesman Jinja delimeters Jinja has two kinds of delimiters. {% ... %} and {{ ... }}. The first one is used to execute statements such as for-loops or assign values, the latter prints the result of the expression to the template. <ul> {%foruserinusers%} <li><ahref="{{user.url}}">{{user.username}}</a>{{user.title}}</li> {%endfor%} </ul> Result:
Using Macros DRY templates with Jinja Macros //macros.html {{%macronav_link(endpoint,name)%} {%ifrequest.endpoint.endswith(endpoint)%} <liclass="active"><ahref="{{url_for(endpoint)}}">{{name}}</a></li> {%else%} <li><ahref="{{url_for(endpoint)}}">{{name}}</a></li> {%endif%} {%endmacro%} //base.html {%from"macros.html"importnav_linkwithcontext%} .. <ulclass="navnavbar-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 fromflaskimportrender_template . @app.route("/") @app.route("/index") defindex(): returnrender_template('index.html')
Iterate the list in the template More Jinja Awesomeness Send a list to our template //app.py .. @app.route("/extns") defextensions(): extns=['Flask','Jinja2','Flask-SQLAlchemy','Flask-Admin', 'Flask-Classy','Flask-Raptor'] returnrender_template('extensions.html',extns=extns) //extensions.html {%extends"base.html"%} {%blockcontent%} <h3>AwesomeFlaskextensions</h3> <br> <ul> {%forextinexts%} <li>{{ext}}</li> {%endfor%} </ul> <h3> Viewmore<ahref="http://flask.pocoo.org/extensions/">Flaskextensions</a> </h3> {%endblock%}
Fun with Gifs! Create an input form to search images Pull an image from giphy api with python Send image and form to template Profit
Create an input form to search images Install Flask-WTF At terminal run: pip install Flask-WTF //forms.py fromflask.ext.wtfimportForm fromwtformsimportStringField fromwtforms.validatorsimportDataRequired classSearchForm(Form): query=StringField('query',validators=[DataRequired()])
Pull an image from giphy api with python importurllib,json importrandom .. defget_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'] returngif
Send the image and form to our template fromformsimportSearchForm app=Flask(__name__) app.secret_key='some_secret_key' .. @app.route("/gifs",methods=['GET','POST']) defgifs(): form=SearchForm() ifform.validate_on_submit(): query=form.query.data gif=get_image(query) returnrender_template('gifs.html',gif=gif,form=form) gif='static/img/dwight.gif' returnrender_template('gifs.html',gif=gif,form=form)
gifs.html template //gifs.html {%extends"base.html"%} {%blockcontent%} <formaction=""method="post"name="query"> {{form.hidden_tag()}} <p> Searchforgifs:<br> {{form.query(size=20)}}<br> {%forerrorinform.query.errors%} <spanstyle="color:red;">[{{error}}]</span> {%endfor%}<br> <inputtype="submit"value="Submit"> </p> </form> <imgsrc="{{gif}}"> {%endblock%}
Links Source code on GitHub Follow me on Twitter Chadev Python Meetup
http://flaskbook.com/ http://blog.miguelgrinberg.com/index http://jinja.pocoo.org/docs/dev/ http://flask.pocoo.org/ https://exploreflask.com/index.html https://www.hakkalabs.co/articles/django-and-flask http://www.fullstackpython.com/flask.html https://pythonhosted.org/Flask-Classy/ http://flask-script.readthedocs.org/en/latest/ https://github.com/realpython/discover-flask Go explore all these things
Questions
THE END

Quick flask an intro to flask