Your SlideShare is downloading. ×
0
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Flask – Python
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Flask – Python

3,800

Published on

Short apresentation about Flask and Python

Short apresentation about Flask and Python

0 Comments
14 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,800
On Slideshare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
Downloads
137
Comments
0
Likes
14
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Max Claus Nunesmaxcnunes@gmail.comhttp://blog.maxcnunes.comhttps://github.com/maxcnunes/flask_bravi
  • 2. FLASK WHAT ?!?!?
  • 3. FLASK IS• Flask is a micro-framework for Python• Easy to code• Easy to configure• Flask won’t make many decisions for you, such as what database to use.• Has an excellent documentation• RESTful• Testable
  • 4. FLASK IS BASED ON WERKZEUG AND JINJA 2 WSGI Template Engine
  • 5. FLASK IS EXTENSIBLE AND KEEPS THE CORE SIMPLE • Flask-Admin • Flask-Restless • Flask-Cache • Flask- • Flask-OpendID SQLAlchemy • Flask-Mail • Flask-Testing • Flask- • Flask-WTF MongoAlchemy • Flask-Uploads
  • 6. FLASK IS OPEN SOURCE
  • 7. LETS CODE
  • 8. CONFIGURING THE ENVIRONMENT
  • 9. VIRTUALENVInstallingpip install virtualenvConfiguringcd ~/YOUR_MAIN_FOLDERmkdir virtualenvscd virtualenvsvirtualenv NAME_YOUR_ENV --no-site-packagesActivating Deactivatingsource NAME_YOUR_ENV/bin/activate deactivate
  • 10. FLASK – THE FIRST APPInstalling pip install FlaskCoding # Import Flask library from flask import Flask # Initialize the app from Flask app = Flask(__name__) hello.py # Define a route to hello_world function @app.route(/) def hello_world(): return Hello World! # Run the app on http://localhost:8085 app.run(debug=True,port=8085)Running python hello.py
  • 11. 6 LINES OF CODE ANDTHIS WORKS
  • 12. LETS GROW THIS APP
  • 13. THE PYTHON SQL ORM
  • 14. SQLALCHEMYInstalling pip install Flask-SqlalchemyCoding the Modelfrom braviapp import db bravibraviappmodels.pyclass News(db.Model): # Define the properties mapped to database columns id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(100), nullable = False) text = db.Column(db.Text, nullable = False) def __init__(self, title, text): self.title = title self.text = text def __repr__(self): return <News %r> % self.title
  • 15. FORMS
  • 16. WTFORMSInstalling pip install Flask-WTFCoding the Form bravibraviappmodels.py# third party importsfrom flask.ext.wtf import Form, TextField, TextAreaField,Requiredclass NewsCreateForm(Form): title = TextField(Title, [Required()]) text = TextAreaField(Text, [Required()])
  • 17. JINJA 2 - TEMPLATES
  • 18. TEMPLATES – BASE HTML<!DOCTYPE html><html> <head> <title>{% block title %}Flask - Bravi{% endblock %}</title> <link rel="stylesheet" href="/static/css/main.css" /> {% block css %}{% endblock %} {% block script %}{% endblock %} </head> <body> bravitemplatesbase.html <div id="wrapper{{ wrapper_type }}"> <div id="header"> {% block header %} <h1><a id="link-title-home" href="{{ url_for(all) }}">Bravi News</a></h1> {% endblock %} </div> <div id="messages"> {% for category, msg in get_flashed_messages(with_categories=true) %} <p class="messages flash-{{ category }}">{{ msg }}</p> {% endfor %} </div> <div id="content" class="shadow"> {% block content %}{% endblock %} </div> <div id="footer">{% block footer %}{% endblock %}</div> </div> </body></html>
  • 19. TEMPLATES – LIST{% extends "base.html" %}{% block content %} <h2>All News</h2> bravitemplatesnews_list.html <ul id="profile-results"> {% for n in news %} <li> <h3>{{ n.title }}</h3> {{ n.text }} </li> {% endfor %} </ul>{% endblock %}{% block footer %} <a class="bt-action bt-action-edit" href="{{url_for(create) }}"> <span>Create</span> </a>{% endblock %}
  • 20. TEMPLATES – CREATE{% extends "base.html" %}{% block content %} bravitemplatesnews_create.html <h2>Create News</h2> {% from "macros.html" import render_field %} <form method="POST" action="." class="form"> {{ form.csrf_token }} {{ render_field(form.title, class="input text") }} {{ render_field(form.text, class="input text") }} <input type="submit" value="Create"> </form>{% endblock %}{% block footer %} <a class="bt-action bt-action-list" href="{{ url_for(all)}}"> <span>News</span> </a>{% endblock %}
  • 21. JINJA 2 – MACROS - DRY{% macro render_field(field) %} <div class="form_field"> bravitemplatesmacros.html {{ field.label(class="label") }} {% if field.errors %} {% set css_class = has_error +kwargs.pop(class, ) %} {{ field(class=css_class, **kwargs) }} <ul class="errors"> {% for error in field.errors %} <li>{{ error|e }}</li> {% endfor %} </ul> {% else %} {{ field(**kwargs) }} {% endif %} </div>{% endmacro %}
  • 22. VIEWSfrom flask import request, flash, redirect, url_for, render_templatefrom braviapp import braviapp, dbfrom braviapp.forms import NewsCreateFormfrom braviapp.models import News@braviapp.errorhandler(404)def not_found(error): flash(You tried access a page that not exists) return redirect(url_for(all)) bravibraviappviews.py@braviapp.route(/)def all(): #from news_model import News news = News.query.all() return render_template(news_list.html, news=news)@braviapp.route(/create/, methods=[GET, POST])def create(): form = NewsCreateForm(request.form) # make sure data are valid if form.validate_on_submit(): news = News(form.title.data, form.text.data) # save on database db.session.add(news) db.session.commit() flash(The news has been created successfully) return redirect(url_for(all)) return render_template(news_create.html, form=form)
  • 23. CORE APP bravibraviapp__init__.PY# third party importsfrom flask import Flaskfrom flask.ext.sqlalchemy import SQLAlchemy# Initialize the app from Flaskbraviapp = Flask(__name__)braviapp.config.from_object(settings)db = SQLAlchemy(braviapp)# local application importsfrom braviapp import views
  • 24. SETTINGS FILEimport os_basedir = os.path.abspath(os.path.dirname(__file__))DEBUG = False bravisettings.pyADMINS = frozenset([youremail@yourdomain.com])SECRET_KEY = SECRET_KEY_FOR_SESSION_SIGNING# Define the path of our database inside the rootapplication, where app.db is the databases nameSQLALCHEMY_DATABASE_URI = sqlite:/// +os.path.join(_basedir, app.db)DATABASE_CONNECT_OPTION = {}CSRF_ENABLED = TrueCSRF_SESSION_KEY = SOMETHING_IMPOSSIBLE_TO_GUEES
  • 25. SQLALCHEMYHelper to reset the database file braviinitialize_db.pyfrom app import db# Drop all tables from db filedb.drop_all()# Create all tables on db file,# copying the structure from the definition on the Modelsdb.create_all()Running python initialize_db.py
  • 26. RUNNINGHelper to initialize the applicationbraviinitialize_app.pyfrom braviapp import braviapp as applicationapplication.run(debug=True,port=8080)Running python initialize_app.pyLETS TRY
  • 27. DEBUGGER
  • 28. PUBLISHING
  • 29. ANYQUESTION?Helpful links:• http://flask.pocoo.org• https://github.com/mitsuhi ko/flask• http://werkzeug.pocoo.org• http://jinja.pocoo.org/docs• http://www.sqlalchemy.org• http://blog.maxcnunes.net• http://www.google.com
  • 30. THANKS

×