SlideShare a Scribd company logo
4
Most read
7
Most read
8
Most read
FLASK - BACKEND COM
PYTHON
SIBELIUS SERAPHINI
2010-2015 Bacharel em Ciências de Computação
2015
Full Stack Developer
O QUE É BACKEND?
Backend
Frontend
Mobile
Database
LET’S CODE
VIRTUALENV
# Cria um virtualenv com nome hello com Python3
mkvirtualenv hello -p /usr/local/bin/python3
# Lista virtualenvs
workon
# inicia virtualenv hello
workon hello
# desativa virtualenv
deactivate
#!/usr/bin/env python3
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello SemComp!'
if __name__ == '__main__':
app.run()
$ pip install Flask
$ python hello.py
* Running on http://localhost:5000/
git clone https://github.com/sibeliusseraphini/hello-flask.git
DEPLOY TO
1. Criar um app no Heroku - heroku apps:create semcomp18
2. Adicionar runtime.txt - python-3.4.2
3. Adicionar Procfile - web: uwsgi uwsgi.ini
4. Install uWSGI - pip install uwsgi
5. Adicionar configuração do uWSGI - uwsgi.ini
6. Criar requirements.txt - pip freeze > requirements.txt
7. Realizar release - git push heroku master
[uwsgi]
http-socket = :$(PORT)
master = true
processes = 8
threads = 4
die-on-term = true
module = hello:app
memory-report = true
offline-threads = 4
harakiri = 500
harakiri-verbose = true
ESTRUTURA FLASK
├── Procfile
├── manage.py
├── requirements.txt
├── runtime.txt
├── semcomp
│   ├── __init__.py
│   ├── api
│   │   ├── __init__.py
│   │   ├── routes.py
│   │   └── tarefa.py
│   ├── main
│   │   ├── __init__.py
│   │   ├── errors.py
│   │   └── views.py
│   ├── models.py
│   ├── static
│   └── templates
│   └── 404.jade
│   └── base.html
└── uwsgi.ini
App Grande
git clone https://github.com/sibeliusseraphini/semcomp-flask.git
BLUEPRINT
api - www.mywebpage.com/api
admin - www.mywebpage.com/admin
mobile - www.mywebpage.com/mobile
•Modular apps
from . import main
from flask import render_template
@main.route('/')
def index():
return "It's working
@main.route('/hello/<name>')
def hello(name):
return render_template('hello.html', name=name)
STATIC FILES + TEMPLATES
from flask import render_template
from . import main
@main.route('/hello/<name>')
def hello(name):
return render_template('hello.html', name=name)
•static files - app/static
•templates - app/templates
JINJA2 - TEMPLATING
<title>{% block title %}{% endblock %}</title>
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
JADE
<!DOCTYPE html>
<html lang="en">
<head>
<title>Jade</title>
<script type="text/javascript">
if (foo) {
bar(1 + 5)
}
</script>
</head>
<body>
<h1>Jade - node template engine</h1>
<div id="container" class="col">
<p>You are amazing</p>
<p>
Jade is a terse and simple
templating language with a
strong focus on performance
and powerful features.
</p>
</div>
</body>
</html>
doctype html
html(lang="en")
head
title= pageTitle
script(type='text/javascript').
if (foo) {
bar(1 + 5)
}
body
h1 Jade - node template engine
#container.col
if youAreUsingJade
p You are amazing
else
p Get on it!
p.
Jade is a terse and simple
templating language with a
strong focus on performance
and powerful features.
PYJADE (JINJA2 + JADE)
app.jinja_env.add_extension(‘pyjade.ext.jinja.PyJadeExtension')
pip install pyjade
ERROR HANDLING
from flask import render_template
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
return render_template('404.jade'), 404
•404 Not Found
•403 Forbidden
•410 Gone
•500 Internal Server Error
EXTENSÕES
Flask-Script - scripts externos
Flask-RESTful - REST APIs fácil
Flask-JWT - autenticação por token JWT
Flask-Weasyprint - HTML as PDF
Flask-Mail - email para Flask
Flask-Login - gerenciamento de sessão de usuário
MONGODB
PyMongo - Mongoengine
REST
GET /api/tarefa - retorna todas as tarefas
GET /api/tarefa/:id - retorna a tarefa :id
PUT /api/tarefa/:id - atualiza a tarefa :id
DELETE /api/tarefa/:id - delete/remove tarefa :id
POST /api/tarefa - cria uma nova tarefa
REST
Sem extensões
REST
Com extensões

More Related Content

PDF
Filling the flask
PPTX
Flask – Python
PDF
Kyiv.py #17 Flask talk
PDF
Flask patterns
PDF
Python RESTful webservices with Python: Flask and Django solutions
PPTX
Flask restfulservices
PDF
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
PDF
Flask Basics
Filling the flask
Flask – Python
Kyiv.py #17 Flask talk
Flask patterns
Python RESTful webservices with Python: Flask and Django solutions
Flask restfulservices
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
Flask Basics

What's hot (20)

KEY
LvivPy - Flask in details
PDF
Flask RESTful Flask HTTPAuth
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
PDF
Web develop in flask
PDF
Rest API using Flask & SqlAlchemy
PDF
Rest api with Python
PDF
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
PDF
Getting Started-with-Laravel
PDF
Flask SQLAlchemy
PDF
Bootstrat REST APIs with Laravel 5
PDF
Laravel Design Patterns
PPT
Dance for the puppet master: G6 Tech Talk
PDF
関西PHP勉強会 php5.4つまみぐい
PDF
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
KEY
Phpne august-2012-symfony-components-friends
PDF
Datagrids with Symfony 2, Backbone and Backgrid
PDF
OSCON Google App Engine Codelab - July 2010
PPTX
REST APIs in Laravel 101
KEY
CodeIgniter 3.0
PDF
Phinx talk
LvivPy - Flask in details
Flask RESTful Flask HTTPAuth
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Web develop in flask
Rest API using Flask & SqlAlchemy
Rest api with Python
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
Getting Started-with-Laravel
Flask SQLAlchemy
Bootstrat REST APIs with Laravel 5
Laravel Design Patterns
Dance for the puppet master: G6 Tech Talk
関西PHP勉強会 php5.4つまみぐい
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Phpne august-2012-symfony-components-friends
Datagrids with Symfony 2, Backbone and Backgrid
OSCON Google App Engine Codelab - July 2010
REST APIs in Laravel 101
CodeIgniter 3.0
Phinx talk
Ad

Similar to Flask - Backend com Python - Semcomp 18 (20)

PPTX
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
PDF
Frameworks da nova Era PHP FuelPHP
PDF
Flask Introduction - Python Meetup
PDF
Python para web - Utilizando micro-framework Flask - PUG-MA
ODP
Pyramid Lighter/Faster/Better web apps
PDF
Symfony2 - OSIDays 2010
PDF
Symfony2 - WebExpo 2010
PDF
Symfony2 - WebExpo 2010
PDF
Prefixルーティングとthemeのススメ
PDF
Laravel 101
PDF
PhpBB meets Symfony2
PDF
Build powerfull and smart web applications with Symfony2
PDF
Modular Test-driven SPAs with Spring and AngularJS
PPTX
Flask & Flask-restx
PDF
Flask intro - ROSEdu web workshops
KEY
GettingStartedWithPHP
PDF
Mojolicious. Веб в коробке!
KEY
Quality Use Of Plugin
ODP
CodeIgniter PHP MVC Framework
PDF
Codeigniter : Two Step View - Concept Implementation
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Frameworks da nova Era PHP FuelPHP
Flask Introduction - Python Meetup
Python para web - Utilizando micro-framework Flask - PUG-MA
Pyramid Lighter/Faster/Better web apps
Symfony2 - OSIDays 2010
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
Prefixルーティングとthemeのススメ
Laravel 101
PhpBB meets Symfony2
Build powerfull and smart web applications with Symfony2
Modular Test-driven SPAs with Spring and AngularJS
Flask & Flask-restx
Flask intro - ROSEdu web workshops
GettingStartedWithPHP
Mojolicious. Веб в коробке!
Quality Use Of Plugin
CodeIgniter PHP MVC Framework
Codeigniter : Two Step View - Concept Implementation
Ad

More from Lar21 (6)

PDF
Acumen Pitch - Sua Ideia na Prática (SINP) São Paulo - SP - Ideation Brasil
PDF
Constrained k means clustering with background knowledge - COP-Kmeans
PDF
Reconhecendo atividades físicas utilizando um smartphone não rigidamente fi...
PDF
Blind Verification of Digital Image Originality: A Statistical Approach
PPT
FlexInterface: a Framework to Provide Flexible Mobile Phone User Interfaces -...
PDF
An Analytic Approach to Evaluate Flexible Mobile User Interfaces for the Elde...
Acumen Pitch - Sua Ideia na Prática (SINP) São Paulo - SP - Ideation Brasil
Constrained k means clustering with background knowledge - COP-Kmeans
Reconhecendo atividades físicas utilizando um smartphone não rigidamente fi...
Blind Verification of Digital Image Originality: A Statistical Approach
FlexInterface: a Framework to Provide Flexible Mobile Phone User Interfaces -...
An Analytic Approach to Evaluate Flexible Mobile User Interfaces for the Elde...

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
A Presentation on Artificial Intelligence
PDF
Electronic commerce courselecture one. Pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
Teaching material agriculture food technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Big Data Technologies - Introduction.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
Per capita expenditure prediction using model stacking based on satellite ima...
Chapter 3 Spatial Domain Image Processing.pdf
Review of recent advances in non-invasive hemoglobin estimation
A Presentation on Artificial Intelligence
Electronic commerce courselecture one. Pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
The Rise and Fall of 3GPP – Time for a Sabbatical?
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Monthly Chronicles - July 2025
Unlocking AI with Model Context Protocol (MCP)
Big Data Technologies - Introduction.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
NewMind AI Weekly Chronicles - August'25 Week I

Flask - Backend com Python - Semcomp 18

  • 1. FLASK - BACKEND COM PYTHON
  • 2. SIBELIUS SERAPHINI 2010-2015 Bacharel em Ciências de Computação 2015 Full Stack Developer
  • 3. O QUE É BACKEND?
  • 6. VIRTUALENV # Cria um virtualenv com nome hello com Python3 mkvirtualenv hello -p /usr/local/bin/python3 # Lista virtualenvs workon # inicia virtualenv hello workon hello # desativa virtualenv deactivate
  • 7. #!/usr/bin/env python3 from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello SemComp!' if __name__ == '__main__': app.run() $ pip install Flask $ python hello.py * Running on http://localhost:5000/ git clone https://github.com/sibeliusseraphini/hello-flask.git
  • 8. DEPLOY TO 1. Criar um app no Heroku - heroku apps:create semcomp18 2. Adicionar runtime.txt - python-3.4.2 3. Adicionar Procfile - web: uwsgi uwsgi.ini 4. Install uWSGI - pip install uwsgi 5. Adicionar configuração do uWSGI - uwsgi.ini 6. Criar requirements.txt - pip freeze > requirements.txt 7. Realizar release - git push heroku master [uwsgi] http-socket = :$(PORT) master = true processes = 8 threads = 4 die-on-term = true module = hello:app memory-report = true offline-threads = 4 harakiri = 500 harakiri-verbose = true
  • 9. ESTRUTURA FLASK ├── Procfile ├── manage.py ├── requirements.txt ├── runtime.txt ├── semcomp │   ├── __init__.py │   ├── api │   │   ├── __init__.py │   │   ├── routes.py │   │   └── tarefa.py │   ├── main │   │   ├── __init__.py │   │   ├── errors.py │   │   └── views.py │   ├── models.py │   ├── static │   └── templates │   └── 404.jade │   └── base.html └── uwsgi.ini App Grande git clone https://github.com/sibeliusseraphini/semcomp-flask.git
  • 10. BLUEPRINT api - www.mywebpage.com/api admin - www.mywebpage.com/admin mobile - www.mywebpage.com/mobile •Modular apps from . import main from flask import render_template @main.route('/') def index(): return "It's working @main.route('/hello/<name>') def hello(name): return render_template('hello.html', name=name)
  • 11. STATIC FILES + TEMPLATES from flask import render_template from . import main @main.route('/hello/<name>') def hello(name): return render_template('hello.html', name=name) •static files - app/static •templates - app/templates
  • 12. JINJA2 - TEMPLATING <title>{% block title %}{% endblock %}</title> <ul> {% for user in users %} <li><a href="{{ user.url }}">{{ user.username }}</a></li> {% endfor %} </ul>
  • 13. JADE <!DOCTYPE html> <html lang="en"> <head> <title>Jade</title> <script type="text/javascript"> if (foo) { bar(1 + 5) } </script> </head> <body> <h1>Jade - node template engine</h1> <div id="container" class="col"> <p>You are amazing</p> <p> Jade is a terse and simple templating language with a strong focus on performance and powerful features. </p> </div> </body> </html> doctype html html(lang="en") head title= pageTitle script(type='text/javascript'). if (foo) { bar(1 + 5) } body h1 Jade - node template engine #container.col if youAreUsingJade p You are amazing else p Get on it! p. Jade is a terse and simple templating language with a strong focus on performance and powerful features.
  • 14. PYJADE (JINJA2 + JADE) app.jinja_env.add_extension(‘pyjade.ext.jinja.PyJadeExtension') pip install pyjade
  • 15. ERROR HANDLING from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.jade'), 404 •404 Not Found •403 Forbidden •410 Gone •500 Internal Server Error
  • 16. EXTENSÕES Flask-Script - scripts externos Flask-RESTful - REST APIs fácil Flask-JWT - autenticação por token JWT Flask-Weasyprint - HTML as PDF Flask-Mail - email para Flask Flask-Login - gerenciamento de sessão de usuário
  • 18. REST GET /api/tarefa - retorna todas as tarefas GET /api/tarefa/:id - retorna a tarefa :id PUT /api/tarefa/:id - atualiza a tarefa :id DELETE /api/tarefa/:id - delete/remove tarefa :id POST /api/tarefa - cria uma nova tarefa