SlideShare a Scribd company logo
7
Most read
8
Most read
16
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
Ad

Recommended

Filling the flask
Filling the flask
Jason Myers
 
Flask – Python
Flask – Python
Max Claus Nunes
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
Alexey Popravka
 
Flask patterns
Flask patterns
it-people
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Flask restfulservices
Flask restfulservices
Marcos Lin
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
CodeCore
 
Flask Basics
Flask Basics
Eueung Mulyana
 
LvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
Web develop in flask
Web develop in flask
Jim Yeh
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
Alessandro Cucci
 
Rest api with Python
Rest api with Python
Santosh Ghimire
 
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Getting Started-with-Laravel
Getting Started-with-Laravel
Mindfire Solutions
 
Flask SQLAlchemy
Flask SQLAlchemy
Eueung Mulyana
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
Laravel Design Patterns
Laravel Design Patterns
Bobby Bouwmann
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
Michael Peacock
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Nina Zakharenko
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
eugenio pombi
 
OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010
ikailan
 
REST APIs in Laravel 101
REST APIs in Laravel 101
Samantha Geitz
 
CodeIgniter 3.0
CodeIgniter 3.0
Phil Sturgeon
 
Phinx talk
Phinx talk
Michael Peacock
 
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Akira Tsuruda
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHP
Dan Jesus
 

More Related Content

What's hot (20)

LvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
Web develop in flask
Web develop in flask
Jim Yeh
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
Alessandro Cucci
 
Rest api with Python
Rest api with Python
Santosh Ghimire
 
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Getting Started-with-Laravel
Getting Started-with-Laravel
Mindfire Solutions
 
Flask SQLAlchemy
Flask SQLAlchemy
Eueung Mulyana
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
Laravel Design Patterns
Laravel Design Patterns
Bobby Bouwmann
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
Michael Peacock
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Nina Zakharenko
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
eugenio pombi
 
OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010
ikailan
 
REST APIs in Laravel 101
REST APIs in Laravel 101
Samantha Geitz
 
CodeIgniter 3.0
CodeIgniter 3.0
Phil Sturgeon
 
Phinx talk
Phinx talk
Michael Peacock
 
LvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
Eueung Mulyana
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
Web develop in flask
Web develop in flask
Jim Yeh
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
Alessandro Cucci
 
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
Laravel Design Patterns
Laravel Design Patterns
Bobby Bouwmann
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
Michael Peacock
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Nina Zakharenko
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
eugenio pombi
 
OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010
ikailan
 
REST APIs in Laravel 101
REST APIs in Laravel 101
Samantha Geitz
 

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

Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Akira Tsuruda
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHP
Dan Jesus
 
Flask Introduction - Python Meetup
Flask Introduction - Python Meetup
Areski Belaid
 
Python para web - Utilizando micro-framework Flask - PUG-MA
Python para web - Utilizando micro-framework Flask - PUG-MA
Herson Leite
 
Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web apps
Dylan Jay
 
Symfony2 - OSIDays 2010
Symfony2 - OSIDays 2010
Fabien Potencier
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
Fabien Potencier
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
Fabien Potencier
 
Prefixルーティングとthemeのススメ
Prefixルーティングとthemeのススメ
Shusuke Otomo
 
Laravel 101
Laravel 101
Commit University
 
PhpBB meets Symfony2
PhpBB meets Symfony2
Fabien Potencier
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
Hugo Hamon
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
Flask & Flask-restx
Flask & Flask-restx
ammaraslam18
 
Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshops
Alex Eftimie
 
GettingStartedWithPHP
GettingStartedWithPHP
Nat Weerawan
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
Anatoly Sharifulin
 
Quality Use Of Plugin
Quality Use Of Plugin
Yasuo Harada
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
Abdul Malik Ikhsan
 
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Akira Tsuruda
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHP
Dan Jesus
 
Flask Introduction - Python Meetup
Flask Introduction - Python Meetup
Areski Belaid
 
Python para web - Utilizando micro-framework Flask - PUG-MA
Python para web - Utilizando micro-framework Flask - PUG-MA
Herson Leite
 
Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web apps
Dylan Jay
 
Prefixルーティングとthemeのススメ
Prefixルーティングとthemeのススメ
Shusuke Otomo
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
Hugo Hamon
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
Flask & Flask-restx
Flask & Flask-restx
ammaraslam18
 
Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshops
Alex Eftimie
 
GettingStartedWithPHP
GettingStartedWithPHP
Nat Weerawan
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
Anatoly Sharifulin
 
Quality Use Of Plugin
Quality Use Of Plugin
Yasuo Harada
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
Abdul Malik Ikhsan
 
Ad

More from Lar21 (6)

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

Recently uploaded (20)

Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 

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