├── Boilerplate ├── blog │ ├── main │ │ ├── __init__.py │ │ └── routes.py │ ├── templates │ │ ├── home.html │ │ └── layout.html │ ├── config.py │ └── __init__.py └── run.py ├── .gitignore ├── Project ├── app │ ├── static │ │ ├── js │ │ │ └── app.js │ │ ├── img │ │ │ ├── flask.png │ │ │ └── uploads │ │ │ │ ├── eye.jpg │ │ │ │ ├── a2bpyfptr0j01.jpg │ │ │ │ ├── D-s0F2yW4AA5i47.jpglarge.jpeg │ │ │ │ └── 5dc0b7399c1f89c45154a5963f976db3.jpg │ │ ├── client │ │ │ ├── img │ │ │ │ ├── 01.jpg │ │ │ │ └── 02.jpg │ │ │ ├── reports │ │ │ │ └── 2017 │ │ │ │ │ └── feb │ │ │ │ │ └── comp │ │ │ │ │ └── computer.pdf │ │ │ └── csv │ │ │ │ └── iris.csv │ │ └── css │ │ │ └── style.css │ ├── templates │ │ ├── macros │ │ │ └── input_macros.html │ │ ├── admin │ │ │ ├── profile.html │ │ │ ├── dashboard.html │ │ │ └── templates │ │ │ │ └── admin_template.html │ │ └── public │ │ │ ├── 500.html │ │ │ ├── 404.html │ │ │ ├── about.html │ │ │ ├── index.html │ │ │ ├── profile.html │ │ │ ├── signup.html │ │ │ ├── sign_up.html │ │ │ ├── upload_image.html │ │ │ ├── guestbook.html │ │ │ ├── templates │ │ │ └── public_template.html │ │ │ └── jinja.html │ ├── admin_views.py │ ├── error_handlers.py │ ├── __init__.py │ └── views.py ├── run.py ├── requirements.txt └── config.py ├── Login ├── login.db └── app.py ├── MusicApp ├── mymusic.db ├── test.py ├── app.py ├── templates │ ├── results.html │ ├── _formhelpers.html │ ├── edit_album.html │ ├── new_album.html │ ├── delete_album.html │ └── index.html ├── tables.py ├── db_setup.py ├── forms.py ├── models.py ├── db_creator.py ├── static │ └── style.css └── main.py ├── Scraping ├── dump.rdb ├── run.py └── app │ ├── __init__.py │ ├── views.py │ ├── tasks.py │ └── templates │ └── add_task.html ├── FlaskAdmin ├── exemplo.db └── app.py ├── FlaskExperimentos.png ├── GraphQL ├── database.sqlite3 ├── app.py ├── schema.py ├── database.py └── models.py ├── FileUpload ├── static │ ├── style.css │ └── upload.js ├── app.py └── templates │ └── upload.html ├── Tasks ├── task.py └── main.py ├── HelloWorld ├── hello.py └── about.py ├── Forms ├── Exemplo2 │ ├── templates │ │ ├── obrigado.html │ │ └── index.html │ └── app.py ├── Exemplo1 │ ├── templates │ │ └── index.html │ └── app.py └── Exemplo3 │ ├── app.py │ └── templates │ └── index.html ├── DateTime ├── app.py └── templates │ └── index.html ├── LiveSearch ├── templates │ └── index.html ├── static │ └── search.js └── app.py ├── jQuery ├── process.py ├── static │ └── js │ │ └── form.js └── templates │ └── form.html ├── FlaskChat ├── main.py └── templates │ └── session.html ├── README.md └── requirements.txt /Boilerplate/blog/main/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .myvenv 2 | myvenv/ 3 | __pycache__/ 4 | -------------------------------------------------------------------------------- /Project/app/static/js/app.js: -------------------------------------------------------------------------------- 1 | console.log('Hello from app.js'); -------------------------------------------------------------------------------- /Login/login.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Login/login.db -------------------------------------------------------------------------------- /Project/run.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | 3 | if __name__ == '__main__': 4 | app.run(debug=True) -------------------------------------------------------------------------------- /MusicApp/mymusic.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/MusicApp/mymusic.db -------------------------------------------------------------------------------- /Scraping/dump.rdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Scraping/dump.rdb -------------------------------------------------------------------------------- /FlaskAdmin/exemplo.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/FlaskAdmin/exemplo.db -------------------------------------------------------------------------------- /FlaskExperimentos.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/FlaskExperimentos.png -------------------------------------------------------------------------------- /GraphQL/database.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/GraphQL/database.sqlite3 -------------------------------------------------------------------------------- /Project/app/static/img/flask.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/img/flask.png -------------------------------------------------------------------------------- /Boilerplate/run.py: -------------------------------------------------------------------------------- 1 | from blog import create_app 2 | 3 | app = create_app() 4 | 5 | if __name__ == '__main__': 6 | app.run(debug=True) -------------------------------------------------------------------------------- /Project/app/static/client/img/01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/client/img/01.jpg -------------------------------------------------------------------------------- /Project/app/static/client/img/02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/client/img/02.jpg -------------------------------------------------------------------------------- /Project/app/static/img/uploads/eye.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/img/uploads/eye.jpg -------------------------------------------------------------------------------- /Project/requirements.txt: -------------------------------------------------------------------------------- 1 | Click==7.0 2 | Flask==1.1.1 3 | itsdangerous==1.1.0 4 | Jinja2==2.11.3 5 | MarkupSafe==1.1.1 6 | Werkzeug==0.15.5 7 | -------------------------------------------------------------------------------- /Boilerplate/blog/templates/home.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block content %} 4 |

Hello World

5 | {% endblock content %} -------------------------------------------------------------------------------- /Project/app/static/img/uploads/a2bpyfptr0j01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/img/uploads/a2bpyfptr0j01.jpg -------------------------------------------------------------------------------- /FileUpload/static/style.css: -------------------------------------------------------------------------------- 1 | body{ 2 | background-color: #24292e; 3 | } 4 | 5 | h2{ 6 | color: white; 7 | } 8 | 9 | #progress_status{ 10 | color: white; 11 | } -------------------------------------------------------------------------------- /Project/app/static/client/reports/2017/feb/comp/computer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/client/reports/2017/feb/comp/computer.pdf -------------------------------------------------------------------------------- /Project/app/static/img/uploads/D-s0F2yW4AA5i47.jpglarge.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/img/uploads/D-s0F2yW4AA5i47.jpglarge.jpeg -------------------------------------------------------------------------------- /Boilerplate/blog/config.py: -------------------------------------------------------------------------------- 1 | class Config: 2 | SECRET_KEY = 'ab57ccec0f56942a5ca33215f9d2d88c' 3 | SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db' # caminho relativo em relação ao nosso arquivo -------------------------------------------------------------------------------- /Project/app/static/img/uploads/5dc0b7399c1f89c45154a5963f976db3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/Project/app/static/img/uploads/5dc0b7399c1f89c45154a5963f976db3.jpg -------------------------------------------------------------------------------- /Scraping/run.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | 3 | # Instalar redis-server 4 | # Executar rq worker 5 | # Navegar até http://localhost:5000/add-task 6 | if __name__ == '__main__': 7 | app.run(debug=True) -------------------------------------------------------------------------------- /MusicApp/test.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from db_setup import init_db 3 | 4 | init_db() 5 | 6 | @app.route('/') 7 | def test(): 8 | return "Welcome to Flask!" 9 | 10 | if __name__ == '__main__': 11 | app.run() -------------------------------------------------------------------------------- /Boilerplate/blog/main/routes.py: -------------------------------------------------------------------------------- 1 | from flask import render_template, request, Blueprint 2 | 3 | main = Blueprint('main', __name__) 4 | 5 | @main.route("/") 6 | @main.route("/home") 7 | def home(): 8 | return render_template('home.html') 9 | -------------------------------------------------------------------------------- /MusicApp/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_sqlalchemy import SQLAlchemy 3 | 4 | app = Flask(__name__) 5 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mymusic.db' 6 | app.secret_key = "flask rocks!" 7 | 8 | db = SQLAlchemy(app) -------------------------------------------------------------------------------- /Scraping/app/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | import redis 3 | from rq import Queue 4 | 5 | app = Flask(__name__) 6 | 7 | r = redis.Redis() 8 | q = Queue(connection=r) 9 | 10 | from app import views 11 | from app import tasks -------------------------------------------------------------------------------- /MusicApp/templates/results.html: -------------------------------------------------------------------------------- 1 | Search Results - Flask Music Database 2 | 3 | 4 | 5 | {{ table }} -------------------------------------------------------------------------------- /Tasks/task.py: -------------------------------------------------------------------------------- 1 | import redis 2 | from rq import Queue 3 | import time 4 | 5 | def background_task(n): 6 | delay = 2 7 | print('Task running') 8 | print(f'Simulating {delay} second delay') 9 | time.sleep(delay) 10 | print(len(n)) 11 | print('Task complete') 12 | return len(n) -------------------------------------------------------------------------------- /HelloWorld/hello.py: -------------------------------------------------------------------------------- 1 | # Importando Flask 2 | from flask import Flask 3 | 4 | # Iniciando a aplicação Flask 5 | app = Flask(__name__) 6 | 7 | # Criando uma rota 8 | @app.route('/') 9 | def index(): 10 | return 'Hello World' 11 | 12 | # Rodando o app 13 | if __name__ == '__main__': 14 | app.run(debug=True) -------------------------------------------------------------------------------- /Project/app/templates/macros/input_macros.html: -------------------------------------------------------------------------------- 1 | {% macro input(label='', type='text', name='', id='', placeholder='') -%} 2 |
3 | 4 | 5 |
6 | {%- endmacro %} -------------------------------------------------------------------------------- /Forms/Exemplo2/templates/obrigado.html: -------------------------------------------------------------------------------- 1 |

Obrigado! Aqui está a informação que você nos forneceu:

2 | 3 | -------------------------------------------------------------------------------- /MusicApp/templates/_formhelpers.html: -------------------------------------------------------------------------------- 1 | {% macro render_field(field) %} 2 |
{{ field.label }} 3 |
{{ field(**kwargs)|safe }} 4 | {% if field.errors %} 5 | 10 | {% endif %} 11 |
12 | {% endmacro %} -------------------------------------------------------------------------------- /Forms/Exemplo1/templates/index.html: -------------------------------------------------------------------------------- 1 | {% if name %} 2 |

Você informou o nome {{ name }}

3 |

Atualize ele no formulário abaixo:

4 | {% else %} 5 |

Por favor, informe o seu nome:

6 | {% endif %} 7 | 8 |
9 | {{ form.hidden_tag() }} 10 | {{ form.name.label }} {{ form.name() }} 11 | {{ form.submit() }} 12 |
13 | -------------------------------------------------------------------------------- /Project/app/admin_views.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flask import render_template 3 | 4 | # Criando uma rota 5 | @app.route('/admin/dashboard') 6 | def admin_dashboard(): 7 | return render_template('admin/dashboard.html') 8 | 9 | # Criando uma nova rota about 10 | @app.route('/admin/profile') 11 | def admin_profile(): 12 | return render_template('admin/profile.html') -------------------------------------------------------------------------------- /Project/app/templates/admin/profile.html: -------------------------------------------------------------------------------- 1 | {% extends 'admin/templates/admin_template.html' %} 2 | 3 | {% block title %}Admin Dashboard{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Profile

10 |
11 |
12 |
13 |
14 | {% endblock main %} -------------------------------------------------------------------------------- /Project/app/templates/public/500.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Error Page{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Server Error 500

10 |
11 |
12 |
13 |
14 | {% endblock main %} -------------------------------------------------------------------------------- /Project/app/error_handlers.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flask import render_template, request 3 | 4 | @app.errorhandler(404) 5 | def not_found(e): 6 | print(e) 7 | return render_template('public/404.html') 8 | 9 | @app.errorhandler(500) 10 | def server_error(e): 11 | app.logger.error(f'Server error: {e}, route: {request.url}') 12 | return render_template('public/500.html') -------------------------------------------------------------------------------- /Project/app/templates/public/404.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Error Page{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Error 404 Not Found

10 |
11 |
12 |
13 |
14 | {% endblock main %} -------------------------------------------------------------------------------- /Project/app/templates/admin/dashboard.html: -------------------------------------------------------------------------------- 1 | {% extends 'admin/templates/admin_template.html' %} 2 | 3 | {% block title %}Admin Dashboard{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Admin Dashboard

10 |
11 |
12 |
13 |
14 | {% endblock main %} -------------------------------------------------------------------------------- /Boilerplate/blog/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_sqlalchemy import SQLAlchemy 3 | from blog.config import Config 4 | 5 | db = SQLAlchemy() 6 | 7 | def create_app(config_class=Config): 8 | app = Flask(__name__) 9 | app.config.from_object(Config) 10 | 11 | db.init_app(app) 12 | 13 | from blog.main.routes import main 14 | app.register_blueprint(main) 15 | 16 | return app -------------------------------------------------------------------------------- /MusicApp/tables.py: -------------------------------------------------------------------------------- 1 | from flask_table import Table, Col, LinkCol 2 | 3 | class Results(Table): 4 | id = Col('Id', show=False) 5 | artist = Col('Artist') 6 | title = Col('Title') 7 | release_date = Col('Release Date') 8 | publisher = Col('Publisher') 9 | media_type = Col('Media') 10 | edit = LinkCol('Edit', 'edit', url_kwargs=dict(id='id')) 11 | delete = LinkCol('Delete', 'delete', url_kwargs=dict(id='id')) -------------------------------------------------------------------------------- /Project/app/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | 5 | if app.config['ENV'] == 'production': 6 | app.config.from_object('config.ProductionConfig') 7 | elif app.config['ENV'] == 'testing': 8 | app.config.from_object('config.TestingConfig') 9 | else: 10 | app.config.from_object('config.DevelopmentConfig') 11 | 12 | from app import views 13 | from app import admin_views 14 | from app import error_handlers -------------------------------------------------------------------------------- /HelloWorld/about.py: -------------------------------------------------------------------------------- 1 | # Importando Flask 2 | from flask import Flask 3 | 4 | # Iniciando a aplicação Flask 5 | app = Flask(__name__) 6 | 7 | # Criando uma rota 8 | @app.route('/') 9 | def index(): 10 | return 'Hello World' 11 | 12 | # Criando uma nova rota about 13 | @app.route('/about') 14 | def about(): 15 | return '

Sobre

' 16 | 17 | # export FLASK_APP=about.py 18 | # flask run 19 | if __name__ == '__main__': 20 | app.run(debug=True) -------------------------------------------------------------------------------- /Project/app/templates/public/about.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Index Page{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

About

10 |
11 | 12 |
13 |
14 |
15 | {% endblock main %} -------------------------------------------------------------------------------- /Project/app/templates/public/index.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Index Page{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Home

10 |
11 | 12 |
13 |
14 |
15 | {% endblock main %} -------------------------------------------------------------------------------- /MusicApp/db_setup.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine 2 | from sqlalchemy.orm import scoped_session, sessionmaker 3 | from sqlalchemy.ext.declarative import declarative_base 4 | 5 | engine = create_engine('sqlite:///mymusic.db', convert_unicode=True) 6 | db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine)) 7 | Base = declarative_base() 8 | Base.query = db_session.query_property() 9 | 10 | def init_db(): 11 | import models 12 | Base.metadata.create_all(bind=engine) -------------------------------------------------------------------------------- /DateTime/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from flask_bootstrap import Bootstrap 3 | from flask_wtf import Form 4 | from wtforms.fields import DateField 5 | 6 | app = Flask(__name__) 7 | app.config['SECRET_KEY'] = 'secret' 8 | Bootstrap(app) 9 | 10 | class MyForm(Form): 11 | date = DateField(id='datepick') 12 | 13 | @app.route('/') 14 | def index(): 15 | form = MyForm() 16 | return render_template('index.html', form=form) 17 | 18 | if __name__ == '__main__': 19 | app.run(debug=True) -------------------------------------------------------------------------------- /Forms/Exemplo2/templates/index.html: -------------------------------------------------------------------------------- 1 |

Bem-vindo a nossa pesquisa!

2 | 3 |
4 | {{ form.hidden_tag() }} 5 | {{ form.name.label }} {{ form.name() }} 6 |
7 | {{ form.saúde.label }} {{ form.saúde() }} 8 |
9 | {{ form.comida.label }} {{ form.comida() }} 10 |
11 | {{ form.humor.label }} {{ form.humor() }} 12 |
13 |

Algum outro feedback?

14 |
15 | {{ form.feedback() }} 16 |
17 | {{ form.submit() }} 18 |
-------------------------------------------------------------------------------- /LiveSearch/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Ajax Live Search 5 | 6 | 7 | 8 | 9 |

Ajax Live Search

10 | 11 |
12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /Project/app/static/css/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color:#2b353f; 3 | opacity: 0.86; 4 | color: white; 5 | } 6 | 7 | textarea{ 8 | resize: none; 9 | } 10 | 11 | .navbar{ 12 | border-bottom: 3px solid black !important; 13 | } 14 | 15 | .nav-link{ 16 | color: black !important; 17 | } 18 | 19 | .card-body{ 20 | color: black !important; 21 | } 22 | 23 | .nav-link:hover{ 24 | color: #007bff !important; 25 | } 26 | 27 | img{ 28 | padding: 5px; 29 | margin-top: 5px; 30 | } 31 | 32 | hr{ 33 | background-color: white; 34 | } 35 | -------------------------------------------------------------------------------- /jQuery/process.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request, jsonify 2 | 3 | app = Flask(__name__) 4 | 5 | @app.route('/') 6 | def index(): 7 | return render_template('form.html') 8 | 9 | @app.route('/process', methods=['POST']) 10 | def process(): 11 | email = request.form['email'] 12 | name = request.form['name'] 13 | 14 | if name and email: 15 | new_name = name[::-1] 16 | return jsonify({'name': new_name}) 17 | 18 | return jsonify({'error': 'Missing data!'}) 19 | 20 | if __name__ == '__main__': 21 | app.run(debug=True) -------------------------------------------------------------------------------- /Project/config.py: -------------------------------------------------------------------------------- 1 | class Config(object): 2 | DEBUG = False 3 | TESTING = False 4 | SECRET_KEY = 'a90fb31x2la1092!5@#!' 5 | DB_NAME = 'production-db' 6 | DB_USERNAME = 'root' 7 | DB_PASSWORD = 'example' 8 | 9 | class ProductionConfig(Config): 10 | pass 11 | 12 | class DevelopmentConfig(Config): 13 | DEBUG = True 14 | 15 | DB_NAME = 'development-db' 16 | DB_USERNAME = 'root' 17 | DB_PASSWORD = 'example' 18 | 19 | class TestingConfig(Config): 20 | TESTING = True 21 | 22 | DB_NAME = 'development-db' 23 | DB_USERNAME = 'root' 24 | DB_PASSWORD = 'example' -------------------------------------------------------------------------------- /MusicApp/forms.py: -------------------------------------------------------------------------------- 1 | from wtforms import Form, StringField, SelectField 2 | 3 | class MusicSearchForm(Form): 4 | choices = [('Artist', 'Artist'),('Album','Album'),('Publisher','Publisher')] 5 | select = SelectField('Search for music:', choices=choices) 6 | search = StringField('') 7 | 8 | class AlbumForm(Form): 9 | media_types = [('Digital','Digital'),('CD','CD'),('DVD','DVD'),('LP','LP')] 10 | artist = StringField('Artist') 11 | title = StringField('Title') 12 | release_date = StringField('Release Date') 13 | publisher = StringField('Publisher') 14 | media_type = SelectField('Media', choices=media_types) -------------------------------------------------------------------------------- /FileUpload/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request, jsonify, make_response 2 | 3 | # Iniciando a aplicação Flask 4 | app = Flask(__name__) 5 | 6 | # Rotas 7 | @app.route('/', methods=['GET', 'POST']) 8 | def upload(): 9 | if request.method == 'POST': 10 | filesize = request.cookies.get('filesize') 11 | file = request.files['file'] 12 | print(f'Filesize: {filesize}') 13 | print(file) 14 | res = make_response(jsonify({'message': f"{file.filename} uploaded"}), 200) 15 | return res 16 | return render_template('upload.html') 17 | 18 | if __name__ == '__main__': 19 | app.run(debug=True) -------------------------------------------------------------------------------- /MusicApp/templates/edit_album.html: -------------------------------------------------------------------------------- 1 | Edit Album - Flask Music Database 2 | 3 | 4 | 5 |

Edit Album

6 | 7 | {% from "_formhelpers.html" import render_field %} 8 |
9 |
10 | {{ render_field(form.artist) }} 11 | {{ render_field(form.title) }} 12 | {{ render_field(form.release_date) }} 13 | {{ render_field(form.publisher) }} 14 | {{ render_field(form.media_type) }} 15 |
16 | 17 |
-------------------------------------------------------------------------------- /MusicApp/templates/new_album.html: -------------------------------------------------------------------------------- 1 | New Album - Flask Music Database 2 | 3 | 4 | 5 |

New Album

6 | 7 | {% from "_formhelpers.html" import render_field %} 8 |
9 |
10 | {{ render_field(form.artist) }} 11 | {{ render_field(form.title) }} 12 | {{ render_field(form.release_date) }} 13 | {{ render_field(form.publisher) }} 14 | {{ render_field(form.media_type) }} 15 |
16 | 17 |
-------------------------------------------------------------------------------- /Forms/Exemplo1/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from flask_wtf import FlaskForm 3 | from wtforms import StringField, SubmitField 4 | 5 | app = Flask(__name__) 6 | app.config['SECRET_KEY'] = 'mysecretkey' 7 | 8 | class InfoForm(FlaskForm): 9 | name = StringField('Qual o seu nome?') 10 | submit = SubmitField('Enviar') 11 | 12 | @app.route('/', methods=['GET','POST']) 13 | def index(): 14 | name = False 15 | form = InfoForm() 16 | 17 | if form.validate_on_submit(): 18 | name = form.name.data 19 | form.name.data = '' 20 | return render_template('index.html',form=form, name=name) 21 | 22 | if __name__ == '__main__': 23 | app.run(debug=True) -------------------------------------------------------------------------------- /MusicApp/templates/delete_album.html: -------------------------------------------------------------------------------- 1 | Delete Album - Flask Music Database 2 | 3 | 4 | 5 |

Delete Album

6 | 7 | {% from "_formhelpers.html" import render_field %} 8 |
9 |
10 | {{ render_field(form.artist) }} 11 | {{ render_field(form.title) }} 12 | {{ render_field(form.release_date) }} 13 | {{ render_field(form.publisher) }} 14 | {{ render_field(form.media_type) }} 15 |
16 | 17 |
-------------------------------------------------------------------------------- /Tasks/main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | from task import * 3 | 4 | # pip install rq 5 | # sudo apt-get install redis-server 6 | # Comando para executar o worker: rq worker 7 | # Requisição para: http://localhost:5000/task?n=20 8 | app = Flask(__name__) 9 | r = redis.Redis() 10 | q = Queue(connection=r) 11 | 12 | @app.route('/task') 13 | def add_task(): 14 | if request.args.get('n'): 15 | job = q.enqueue(background_task, request.args.get('n')) 16 | 17 | q_len = len(q) 18 | 19 | return f'Task {job.id} added to queue at {job.enqueued_at}. {q_len} tasks in the queue' 20 | 21 | return 'No value for n' 22 | 23 | if __name__ == '__main__': 24 | app.run(debug=True) -------------------------------------------------------------------------------- /LiveSearch/static/search.js: -------------------------------------------------------------------------------- 1 | function live_search(value){ 2 | value = value.trim(); 3 | if(value != "") { 4 | $.ajax({ 5 | url: "search", 6 | data: {search_text: value}, 7 | dataType: "json", 8 | success: function(data){ 9 | let res = ""; 10 | for(i in data.results){ 11 | res += 12 | ` 13 |
14 | ${data.results[i]} 15 |
16 | `; 17 | } 18 | $("#results").html(res); 19 | } 20 | }); 21 | } 22 | else { 23 | $("#results").html(""); 24 | } 25 | } -------------------------------------------------------------------------------- /MusicApp/models.py: -------------------------------------------------------------------------------- 1 | from app import db 2 | 3 | class Artist(db.Model): 4 | __tablename__ = "artists" 5 | 6 | id = db.Column(db.Integer, primary_key=True) 7 | name = db.Column(db.String) 8 | 9 | def __repr__(self): 10 | return "{}".format(self.name) 11 | 12 | class Album(db.Model): 13 | __tablename__ = "albums" 14 | 15 | id = db.Column(db.Integer, primary_key=True) 16 | title = db.Column(db.String) 17 | release_date = db.Column(db.String) 18 | publisher = db.Column(db.String) 19 | media_type = db.Column(db.String) 20 | 21 | artist_id = db.Column(db.Integer, db.ForeignKey("artists.id")) 22 | artist = db.relationship("Artist", backref=db.backref("albums", order_by=id), lazy=True) -------------------------------------------------------------------------------- /Scraping/app/views.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from app.tasks import count_words 3 | from app import q 4 | from flask import render_template, request 5 | from time import strftime 6 | 7 | @app.route('/') 8 | def index(): 9 | return 'Hello World' 10 | 11 | @app.route('/add-task', methods=['GET','POST']) 12 | def add_task(): 13 | jobs = q.jobs 14 | message = None 15 | 16 | if request.args: 17 | url = request.args.get('url') 18 | task = q.enqueue(count_words, url) 19 | jobs = q.jobs 20 | q_len = len(q) 21 | message = f'Task queued at {task.enqueued_at.strftime("%a %d %b %Y %H:%M:%S")}. {q_len} jobs queued' 22 | 23 | return render_template('add_task.html', message=message, jobs=jobs) -------------------------------------------------------------------------------- /jQuery/static/js/form.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | $('form').on('submit', function(event){ 3 | $.ajax({ 4 | data : { 5 | name : $('#nameInput').val(), 6 | email : $('#emailInput').val() 7 | }, 8 | type : 'POST', 9 | url : '/process' 10 | }) 11 | .done(function(data){ 12 | if(data.error){ 13 | $('#errorAlert').text(data.error).show(); 14 | $('#successAlert').hide(); 15 | } else { 16 | $('#successAlert').text(data.name).show(); 17 | $('#errorAlert').hide(); 18 | } 19 | }); 20 | event.preventDefault(); 21 | }); 22 | }); -------------------------------------------------------------------------------- /Forms/Exemplo3/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, flash, session, redirect, url_for 2 | from flask_wtf import FlaskForm 3 | from wtforms import StringField, SubmitField 4 | 5 | app = Flask(__name__) 6 | 7 | app.config['SECRET_KEY'] = 'kmykey' 8 | 9 | class SimpleForm(FlaskForm): 10 | name = StringField('Qual o seu nome?') 11 | submit = SubmitField('Enviar') 12 | 13 | @app.route('/', methods=['GET','POST']) 14 | def index(): 15 | form = SimpleForm() 16 | 17 | if form.validate_on_submit(): 18 | session['name'] = form.name.data 19 | flash(f'Você alterou o seu nome para: {session["name"]}') 20 | 21 | return redirect(url_for('index')) 22 | 23 | return render_template('index.html', form=form) 24 | 25 | if __name__ == '__main__': 26 | app.run(debug=True) -------------------------------------------------------------------------------- /Scraping/app/tasks.py: -------------------------------------------------------------------------------- 1 | from urllib import request 2 | from bs4 import BeautifulSoup 3 | import lxml 4 | import time 5 | 6 | def count_words(url): 7 | print(f'Counting words at {url}') 8 | time.sleep(2) 9 | start = time.time() 10 | r = request.urlopen(url) 11 | soup = BeautifulSoup(r.read().decode(), 'lxml') 12 | paragraphs = ' '.join([p.text for p in soup.find_all('p')]) 13 | word_count = dict() 14 | for i in paragraphs.split(): 15 | if not i in word_count: 16 | word_count[i] = 1 17 | else: 18 | word_count[i] += 1 19 | 20 | end = time.time() 21 | 22 | time_elapsed = end - start 23 | print(word_count) 24 | print(f'Total words: {len(word_count)}') 25 | print(f'Time ealpsed: {time_elapsed}') 26 | 27 | return len(word_count) -------------------------------------------------------------------------------- /FlaskChat/main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from flask_socketio import SocketIO 3 | 4 | # Instalar: 5 | # pip install python-socketio==4.3.1 6 | # pip install python-engineio==3.10.0 7 | # pip install Flask-SocketIO==4.2.1 8 | app = Flask(__name__) 9 | app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#' 10 | socketio = SocketIO(app) 11 | 12 | @app.route('/') 13 | def sessions(): 14 | return render_template('session.html') 15 | 16 | def messageReceived(methods=['GET', 'POST']): 17 | print('message was received!!!') 18 | 19 | @socketio.on('my event') 20 | def handle_my_custom_event(json, methods=['GET', 'POST']): 21 | print('received my event: ' + str(json)) 22 | socketio.emit('my response', json, callback=messageReceived) 23 | 24 | if __name__ == '__main__': 25 | socketio.run(app, debug=True) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Experimentos Flask 2 | 3 | ![img](https://raw.githubusercontent.com/the-akira/FlaskExperimentos/master/FlaskExperimentos.png) 4 | 5 | Experimentos diversos com **[Flask](https://flask.palletsprojects.com/en/2.0.x/)**: exemplos, tutoriais e pequenos apps. 6 | 7 | ### Instalação 8 | 9 | Para experimentar os códigos, primeiro crie um clone do repositório: 10 | 11 | ``` 12 | git clone https://github.com/the-akira/FlaskExperimentos.git 13 | ``` 14 | 15 | Dentro do diretório principal: 16 | 17 | Crie um Ambiente Virtual 18 | 19 | ``` 20 | python -m venv myvenv 21 | ``` 22 | 23 | Ative o Ambiente Virtual 24 | 25 | ``` 26 | source myvenv/bin/activate 27 | ``` 28 | 29 | Instale as dependências necessárias: 30 | 31 | ``` 32 | pip install -r requirements.txt 33 | ``` 34 | 35 | Navegue até o aplicativo que você deseja testar e siga as instruções. 36 | -------------------------------------------------------------------------------- /GraphQL/app.py: -------------------------------------------------------------------------------- 1 | from database import db_session, init_db 2 | from flask import Flask 3 | from schema import schema 4 | from flask_graphql import GraphQLView 5 | 6 | app = Flask(__name__) 7 | app.debug = True 8 | 9 | # Visitar 'http://localhost:5000/graphql' e executar a query 10 | query = """ 11 | { 12 | allEmployees(sort: [NAME_ASC, ID_ASC]) { 13 | edges { 14 | node { 15 | id 16 | name 17 | department { 18 | id 19 | name 20 | } 21 | role { 22 | id 23 | name 24 | } 25 | } 26 | } 27 | } 28 | } 29 | """ 30 | 31 | app.add_url_rule( 32 | "/graphql", view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True) 33 | ) 34 | 35 | @app.teardown_appcontext 36 | def shutdown_session(exception=None): 37 | db_session.remove() 38 | 39 | if __name__ == "__main__": 40 | init_db() 41 | app.run() -------------------------------------------------------------------------------- /LiveSearch/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, render_template 2 | import json 3 | 4 | app = Flask(__name__) 5 | 6 | LANGUAGES = [ 7 | 'Python', 8 | 'PHP', 9 | 'C', 10 | 'C++', 11 | 'Javascript', 12 | 'LISP', 13 | 'FORTRAN', 14 | 'C#', 15 | 'Java', 16 | 'Haskell', 17 | 'Assembly', 18 | 'Elixir', 19 | 'Go', 20 | 'COBOL', 21 | 'Ruby', 22 | 'Clojure', 23 | 'Erlang', 24 | 'Julia', 25 | 'Objective-C', 26 | 'Pascal', 27 | 'Bash', 28 | 'OCaml' 29 | ] 30 | 31 | # Routes 32 | @app.route("/") 33 | def index(): 34 | return render_template("index.html") 35 | 36 | @app.route("/search") 37 | def search(): 38 | text = request.args['search_text'] 39 | result = [c for c in LANGUAGES if str(text).lower() in c.lower()] 40 | return json.dumps({"results":result}) 41 | 42 | if __name__ == "__main__": 43 | app.run(debug=True) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aniso8601==7.0.0 2 | Babel==2.9.1 3 | beautifulsoup4==4.8.0 4 | certifi==2019.6.16 5 | chardet==3.0.4 6 | Click==7.0 7 | dominate==2.4.0 8 | Flask==1.1.1 9 | Flask-Admin==1.5.4 10 | Flask-Babel==0.12.2 11 | Flask-Bootstrap==3.3.7.1 12 | Flask-GraphQL==2.0.0 13 | Flask-Login==0.4.1 14 | Flask-MySQLdb==0.2.0 15 | Flask-SocketIO==4.2.1 16 | Flask-SQLAlchemy==2.4.0 17 | Flask-Table==0.5.0 18 | Flask-WTF==0.14.2 19 | graphene==2.1.8 20 | graphene-sqlalchemy==2.2.2 21 | graphql-core==2.2.1 22 | graphql-relay==2.0.0 23 | graphql-server-core==1.1.1 24 | idna==2.8 25 | itsdangerous==1.1.0 26 | Jinja2==2.11.3 27 | lxml==4.9.1 28 | MarkupSafe==1.1.1 29 | mysqlclient==1.4.4 30 | promise==2.2.1 31 | python-engineio==3.10.0 32 | python-socketio==4.3.1 33 | pytz==2019.3 34 | redis==3.3.8 35 | requests==2.22.0 36 | rq==1.1.0 37 | Rx==1.6.1 38 | singledispatch==3.4.0.3 39 | six==1.13.0 40 | soupsieve==1.9.2 41 | SQLAlchemy==1.3.7 42 | urllib3==1.26.5 43 | visitor==0.1.3 44 | Werkzeug==0.15.5 45 | WTForms==2.2.1 46 | -------------------------------------------------------------------------------- /MusicApp/db_creator.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine, ForeignKey 2 | from sqlalchemy import Column, Integer, String 3 | from sqlalchemy.ext.declarative import declarative_base 4 | from sqlalchemy.orm import relationship, backref 5 | 6 | engine = create_engine('sqlite:///mymusic.db', echo=True) 7 | Base = declarative_base() 8 | 9 | class Artist(Base): 10 | __tablename__ = "artists" 11 | 12 | id = Column(Integer, primary_key=True) 13 | name = Column(String) 14 | 15 | def __repr__(self): 16 | return "{}".format(self.name) 17 | 18 | 19 | class Album(Base): 20 | __tablename__ = "albums" 21 | 22 | id = Column(Integer, primary_key=True) 23 | title = Column(String) 24 | release_date = Column(String) 25 | publisher = Column(String) 26 | media_type = Column(String) 27 | 28 | artist_id = Column(Integer, ForeignKey("artists.id")) 29 | artist = relationship("Artist", backref=backref("albums", order_by=id)) 30 | 31 | # Cria tabelas 32 | Base.metadata.create_all(engine) -------------------------------------------------------------------------------- /Project/app/templates/public/profile.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Profile{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Profile

10 |
11 |
12 |
13 |

{{ username }}

14 |
15 | {% if user %} 16 |

{{ user['name'] }}

17 |

{{ user['bio'] }}

18 |

{{ user['twitter'] }}

19 | {% else %} 20 |

User not found!

21 | {% endif %} 22 |
23 |
24 |
25 |
26 |
27 | {% endblock main %} -------------------------------------------------------------------------------- /MusicApp/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | Flask Music Database 3 | 4 | 5 | 6 | 7 | 8 |

Flask Music Database

9 | 10 | {% with messages = get_flashed_messages() %} 11 | {% if messages %} 12 | 17 | {% endif %} 18 | {% endwith %} 19 | 20 |
21 | New Album 22 | {% for q in qry %} 23 |

{{ q.title }} - {{ q.artist }}

24 | {% endfor %} 25 | {% from "_formhelpers.html" import render_field %} 26 |
27 |
28 | {{ render_field(form.select) }} 29 | {{ render_field(form.search) }} 30 |
31 | 32 |
33 |
34 | -------------------------------------------------------------------------------- /DateTime/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "bootstrap/base.html" %} 2 | {% import "bootstrap/wtf.html" as wtf %} 3 | 4 | {% block title %}This is an example page{% endblock %} 5 | 6 | {% block head %} 7 | {{ super() }} 8 | 9 | {% endblock %} 10 | 11 | {% block content %} 12 |
13 |

Date Time Picker

14 |
15 |
16 |
17 | {{ wtf.quick_form(form) }} 18 |
19 |
20 |
21 | {% endblock %} 22 | 23 | {% block scripts %} 24 | {{ super() }} 25 | 26 | 27 | 32 | {% endblock %} -------------------------------------------------------------------------------- /Project/app/templates/public/signup.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Sign Up{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Sign Up

10 |
11 |
12 |
13 | 14 | 15 |
16 |
17 | 18 | 19 |
20 |
21 | 22 | 23 |
24 | 25 |
26 |
27 |
28 |
29 | {% endblock main %} -------------------------------------------------------------------------------- /Project/app/templates/public/sign_up.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Sign Up{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Sign Up

10 |
11 |
12 |
13 | 14 | 15 |
16 |
17 | 18 | 19 |
20 |
21 | 22 | 23 |
24 | 25 |
26 |
27 |
28 |
29 | {% endblock main %} -------------------------------------------------------------------------------- /Boilerplate/blog/templates/layout.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | {% block content %}{% endblock %} 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /GraphQL/schema.py: -------------------------------------------------------------------------------- 1 | from graphene_sqlalchemy import SQLAlchemyConnectionField, SQLAlchemyObjectType 2 | from graphene import relay 3 | import graphene 4 | from models import Department as DepartmentModel 5 | from models import Employee as EmployeeModel 6 | from models import Role as RoleModel 7 | 8 | class Department(SQLAlchemyObjectType): 9 | class Meta: 10 | model = DepartmentModel 11 | interfaces = (relay.Node,) 12 | 13 | class Employee(SQLAlchemyObjectType): 14 | class Meta: 15 | model = EmployeeModel 16 | interfaces = (relay.Node,) 17 | 18 | class Role(SQLAlchemyObjectType): 19 | class Meta: 20 | model = RoleModel 21 | interfaces = (relay.Node,) 22 | 23 | class Query(graphene.ObjectType): 24 | node = relay.Node.Field() 25 | # Permitir apenas ordenação de coluna única 26 | all_employees = SQLAlchemyConnectionField(Employee, sort=Employee.sort_argument()) 27 | # Permite a ordenação em várias colunas, por padrão na chave primária 28 | all_roles = SQLAlchemyConnectionField(Role) 29 | # Desativa a ordenação neste campo 30 | all_departments = SQLAlchemyConnectionField(Department, sort=None) 31 | 32 | schema = graphene.Schema(query=Query, types=[Department, Employee, Role]) -------------------------------------------------------------------------------- /Login/app.py: -------------------------------------------------------------------------------- 1 | from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user 2 | from flask import Flask 3 | from flask_sqlalchemy import SQLAlchemy 4 | 5 | # >>> from app import db, User 6 | # >>> db.create_all() 7 | # >>> gabriel = User(username='Gabriel') 8 | # >>> db.session.add(gabriel) 9 | # >>> db.session.commit() 10 | # >>> results = User.query.all() 11 | app = Flask(__name__) 12 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///login.db' 13 | app.config['SECRET_KEY'] = 'chave-secreta' 14 | 15 | db = SQLAlchemy(app) 16 | login_manager = LoginManager() 17 | login_manager.init_app(app) 18 | 19 | class User(db.Model, UserMixin): 20 | id = db.Column(db.Integer, primary_key=True) 21 | username = db.Column(db.String(30), unique=True) 22 | 23 | @login_manager.user_loader 24 | def load_user(user_id): 25 | return User.query.get(int(user_id)) 26 | 27 | @app.route('/') 28 | def index(): 29 | user = User.query.filter_by(username='Gabriel').first() 30 | login_user(user) 31 | return 'You are now logged in...' 32 | 33 | @app.route('/logout') 34 | @login_required 35 | def logout(): 36 | logout_user() 37 | return 'You are now logged out!' 38 | 39 | @app.route('/home') 40 | @login_required 41 | def home(): 42 | return f'O usuário atual é {current_user.username}' 43 | 44 | if __name__ == '__main__': 45 | app.run(debug=True) -------------------------------------------------------------------------------- /Project/app/templates/public/upload_image.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Upload Image{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Upload Image

10 |
11 | 12 |
13 |
14 |
15 | 16 | 17 |
18 |
19 | 20 |
21 |
22 |
23 |
24 | {% endblock main %} 25 | 26 | {% block script %} 27 | 33 | 38 | {% endblock script %} -------------------------------------------------------------------------------- /Forms/Exemplo2/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, session, redirect, url_for 2 | from flask_wtf import FlaskForm 3 | from wtforms import (StringField, BooleanField, DateTimeField, RadioField, SelectField, TextField, TextAreaField, SubmitField) 4 | from wtforms.validators import DataRequired 5 | 6 | app = Flask(__name__) 7 | app.config['SECRET_KEY'] = 'mysecretkey' 8 | 9 | class InfoForm(FlaskForm): 10 | name = StringField('Quem é você?', validators=[DataRequired()]) 11 | saúde = BooleanField('Você está bem de saúde?') 12 | humor = RadioField('Por favor, escolha o seu humor:', choices=[('Feliz','Feliz'),('Alegre','Alegre')]) 13 | comida = SelectField('Escolha seu alimento favorito:',choices=[('Arroz','Arroz'),('Batata','Batata'),('Banana','Banana')]) 14 | feedback = TextAreaField() 15 | submit = SubmitField('enviar') 16 | 17 | @app.route('/', methods=['GET','POST']) 18 | def index(): 19 | form = InfoForm() 20 | if form.validate_on_submit(): 21 | session['name'] = form.name.data 22 | session['saúde'] = form.saúde.data 23 | session['humor'] = form.humor.data 24 | session['comida'] = form.comida.data 25 | session['feedback'] = form.feedback.data 26 | 27 | return redirect(url_for('obrigado')) 28 | 29 | return render_template('index.html', form=form) 30 | 31 | @app.route('/obrigado') 32 | def obrigado(): 33 | return render_template('obrigado.html') 34 | 35 | if __name__ == '__main__': 36 | app.run(debug=True) -------------------------------------------------------------------------------- /GraphQL/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy.orm import scoped_session, sessionmaker 4 | 5 | engine = create_engine('sqlite:///database.sqlite3', convert_unicode=True) 6 | db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine)) 7 | Base = declarative_base() 8 | Base.query = db_session.query_property() 9 | 10 | def init_db(): 11 | """ 12 | Importe todos os módulos aqui que possam definir modelos 13 | para que sejam registrados corretamente nos metadados. 14 | Caso contrário, você terá que importá-los antes de chamar init_db() 15 | """ 16 | from models import Department, Employee, Role 17 | Base.metadata.drop_all(bind=engine) 18 | Base.metadata.create_all(bind=engine) 19 | 20 | # Cria as fixtures 21 | engenharia = Department(name='Engenharia') 22 | db_session.add(engenharia) 23 | rh = Department(name='Recursos Humanos') 24 | db_session.add(rh) 25 | 26 | gerente = Role(name='gerente') 27 | db_session.add(gerente) 28 | engenheiro = Role(name='engenheiro') 29 | db_session.add(engenheiro) 30 | 31 | gabriel = Employee(name='Gabriel', department=engenharia, role=engenheiro) 32 | db_session.add(gabriel) 33 | rafael = Employee(name='Rafael', department=engenharia, role=engenheiro) 34 | db_session.add(rafael) 35 | maria = Employee(name='Maria', department=rh, role=gerente) 36 | db_session.add(maria) 37 | db_session.commit() -------------------------------------------------------------------------------- /Forms/Exemplo3/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Formulário 5 | 6 | 7 | 8 | 9 | {% for mess in get_flashed_messages() %} 10 | 16 | {% endfor %} 17 | 18 |
19 | {{ form.hidden_tag() }} 20 | {{ form.name.label }} {{ form.name() }} 21 | {{ form.submit() }} 22 |
23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /jQuery/templates/form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | AJAX Example 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 |



13 |
14 |
15 | 16 | 17 |
18 |
19 | 20 | 21 |
22 | 23 |
24 |
25 | 26 | 27 |
28 | 29 | -------------------------------------------------------------------------------- /FlaskChat/templates/session.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Flask Chat App 4 | 5 | 6 | 7 |

No message yet..

8 |
9 | 10 |
11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 44 | 45 | -------------------------------------------------------------------------------- /FlaskAdmin/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, redirect, url_for 2 | from flask_sqlalchemy import SQLAlchemy 3 | from flask_admin import Admin, AdminIndexView 4 | from flask_admin.contrib.sqla import ModelView 5 | from flask_login import UserMixin, LoginManager, current_user, login_user, logout_user 6 | 7 | # Para logar, acessar: http://localhost:5000/login 8 | # Para acessar o painel admin: http://localhost:5000/admin 9 | # Para deslogar: http://localhost:5000/logout 10 | # >>> from app import db, User 11 | # >>> db.create_all() 12 | # >>> gabriel = User(name='Gabriel') 13 | # >>> db.session.add(gabriel) 14 | # >>> db.session.commit() 15 | 16 | app = Flask(__name__) 17 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///exemplo.db' 18 | app.config['SECRET_KEY'] = 'secret' 19 | 20 | db = SQLAlchemy(app) 21 | login = LoginManager(app) 22 | 23 | @login.user_loader 24 | def load_user(user_id): 25 | return User.query.get(user_id) 26 | 27 | class User(db.Model, UserMixin): 28 | id = db.Column(db.Integer, primary_key=True) 29 | name = db.Column(db.String(30)) 30 | 31 | class MyModelView(ModelView): 32 | def is_accessible(self): 33 | return current_user.is_authenticated 34 | 35 | def inaccessible_callback(self, name, **kwargs): 36 | return redirect(url_for('login')) 37 | 38 | class MyAdminIndexView(AdminIndexView): 39 | def is_accessible(self): 40 | return current_user.is_authenticated 41 | 42 | admin = Admin(app, index_view=MyAdminIndexView()) 43 | admin.add_view(MyModelView(User, db.session)) 44 | 45 | @app.route('/login') 46 | def login(): 47 | user = User.query.get(1) 48 | login_user(user) 49 | return 'Logged In' 50 | 51 | @app.route('/logout') 52 | def logout(): 53 | logout_user() 54 | return 'Logged Out' 55 | 56 | if __name__ == '__main__': 57 | app.run(debug=True, port=5000) -------------------------------------------------------------------------------- /Project/app/templates/public/guestbook.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% block title %}Guestbook Page{% endblock title %} 4 | 5 | {% block main %} 6 |
7 |
8 |
9 |

Guestbook

10 |
11 | 12 |
13 |
14 | 15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 |
23 |
24 |
25 |
26 | {% endblock main %} 27 | 28 | {% block script %} 29 | 57 | {% endblock script %} -------------------------------------------------------------------------------- /GraphQL/models.py: -------------------------------------------------------------------------------- 1 | from database import Base 2 | from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, func 3 | from sqlalchemy.orm import backref, relationship 4 | 5 | class Department(Base): 6 | __tablename__ = 'department' 7 | id = Column(Integer, primary_key=True) 8 | name = Column(String) 9 | 10 | class Role(Base): 11 | __tablename__ = 'roles' 12 | role_id = Column(Integer, primary_key=True) 13 | name = Column(String) 14 | 15 | class Employee(Base): 16 | __tablename__ = 'employee' 17 | id = Column(Integer, primary_key=True) 18 | name = Column(String) 19 | # Use default=func.now() para definir o tempo de contratação padrão 20 | # de um funcionário para ser a hora atual quando um registro de funcionário for criado 21 | hired_on = Column(DateTime, default=func.now()) 22 | department_id = Column(Integer, ForeignKey('department.id')) 23 | role_id = Column(Integer, ForeignKey('roles.role_id')) 24 | # Use cascade='delete,all' para propagar a exclusão de um departamento para seus funcionários 25 | department = relationship( 26 | Department, 27 | backref=backref('employees', 28 | uselist=True, 29 | cascade='delete,all')) 30 | role = relationship( 31 | Role, 32 | backref=backref('roles', 33 | uselist=True, 34 | cascade='delete,all')) 35 | 36 | # Importando tudo que é necessário 37 | # >>> from database import engine, db_session 38 | # >>> from models import Base, Department, Employee 39 | # >>> Base.metadata.create_all(bind=engine) 40 | 41 | # Preenchendo as tabelas com dados 42 | # >>> engenharia = Department(name='Engenharia') 43 | # >>> db_session.add(engenharia) 44 | # >>> rh = Department(name='Recursos Humanos') 45 | # >>> db_session.add(rh) 46 | # >>> gabriel = Employee(name='Gabriel', department=engenharia) 47 | # >>> db_session.add(gabriel) 48 | # >>> rafael = Employee(name='Rafael', department=engenharia) 49 | # >>> db_session.add(rafael) 50 | # >>> maria = Employee(name='Maria', department=rh) 51 | # >>> db_session.add(maria) 52 | # >>> db_session.commit() -------------------------------------------------------------------------------- /MusicApp/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background: #0D0D0D; 3 | color: #EDEDED; 4 | } 5 | 6 | h2 { 7 | margin-top: 20px; 8 | text-align: center; 9 | font-size: 2.0rem; 10 | } 11 | 12 | div { 13 | margin: 0 auto; 14 | text-align: center; 15 | } 16 | 17 | .btn { 18 | padding: 10px; 19 | color: white; 20 | background: #3F3F3F; 21 | font-size: 1.2rem; 22 | border: 2px solid white; 23 | text-decoration: none; 24 | } 25 | 26 | p { 27 | margin-top: 30px; 28 | text-align: center; 29 | font-size: 1.2rem; 30 | } 31 | 32 | a { 33 | color: white; 34 | } 35 | 36 | dd { 37 | margin-inline-start: 0px; 38 | } 39 | 40 | form { 41 | text-align: center; 42 | margin: 0 auto; 43 | background: #3F3F3F; 44 | width: 30%; 45 | border: 2px solid white; 46 | } 47 | 48 | label { 49 | font-size: 1.13rem; 50 | } 51 | 52 | ul > li { 53 | text-align: center; 54 | list-style: none; 55 | margin-bottom: 30px; 56 | font-size: 1.3rem; 57 | } 58 | 59 | input[type="submit"] { 60 | margin-bottom: 15px; 61 | padding: 10px 15px 10px 15px; 62 | color: white; 63 | background: #303030; 64 | font-size: 1.2rem; 65 | border: 2px solid white; 66 | font-weight: bold; 67 | } 68 | 69 | input[type="text"] { 70 | height: 28px; 71 | margin-top: 6.5px; 72 | margin-bottom: 6.5px; 73 | border: 2px solid black; 74 | } 75 | 76 | select[id="select"] { 77 | margin-top: 7px; 78 | margin-bottom: 7px; 79 | height: 28px; 80 | } 81 | 82 | select[id="media_type"] { 83 | margin-top: 7px; 84 | height: 28px; 85 | } 86 | 87 | table { 88 | margin-left: auto; 89 | margin-right: auto; 90 | width: 100%; 91 | border-collapse: collapse; 92 | } 93 | 94 | table, th, td { 95 | border: 1px solid white; 96 | } 97 | 98 | th, td { 99 | padding: 10px; 100 | text-align: center; 101 | font-size: 1.3rem; 102 | background: #303030; 103 | } 104 | 105 | @media screen and (max-width: 750px) { 106 | form { 107 | width: 80%; 108 | } 109 | } -------------------------------------------------------------------------------- /Scraping/app/templates/add_task.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Scraper 10 | 11 | 12 |
13 |
14 |
15 |
Word counter
16 |
17 |
18 |
19 |
20 | 21 | 22 | {% if message %} 23 | {{ message }} 24 | {% endif %} 25 |
26 | 27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
Job queue
37 | {% if jobs %} 38 | {% for job in jobs %} 39 |
40 |
41 |
{{ job.func_name }}
42 |

Args: {{ job.args }}

43 | Job ID: {{ job.id }} 44 | Status: {{ job.status }} 45 | Created at: {{ job.created_at.strftime('%a, %d %b %Y %H:%M:%S') }} 46 | Enqueued at: {{ job.enqueued_at.strftime('%a, %d %b %Y %H:%M:%S') }} 47 |
48 |
49 | {% endfor %} 50 | {% else %} 51 |

No jobs in the queue

52 | {% endif %} 53 |
54 |
55 |
56 | 57 | -------------------------------------------------------------------------------- /Project/app/templates/admin/templates/admin_template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% block title %}{% endblock title %} 15 | 16 | 17 | 18 | 44 | 45 |
46 | {% block main %}{% endblock main %} 47 |
48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /FileUpload/templates/upload.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Upload Video 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |
17 |

Upload your file...

18 | 19 |
20 |
21 | 22 | 23 |
24 |
25 | 26 | 27 | 28 | 32 | 33 | 34 | 35 |
36 | 37 |
38 |
39 |
40 |
41 | 42 |
43 |
44 |
45 |
46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /FileUpload/static/upload.js: -------------------------------------------------------------------------------- 1 | let progress = document.getElementById('progress') 2 | let progress_wrapper = document.getElementById('progress_wrapper') 3 | let progress_status = document.getElementById('progress_status') 4 | 5 | let upload_btn = document.getElementById('upload_btn') 6 | let loading_btn = document.getElementById('loading_btn') 7 | let cancel_btn = document.getElementById('cancel_btn') 8 | 9 | let input = document.getElementById('file_input') 10 | let file_input_label = document.getElementById('file_input_label') 11 | 12 | function show_alert(message, alert){ 13 | alert_wrapper.innerHTML = ` 14 | 20 | `; 21 | }; 22 | 23 | function input_filename(){ 24 | file_input_label.innerText = input.files[0].name; 25 | }; 26 | 27 | function upload(url){ 28 | if(!input.value){ 29 | show_alert('No file selected', 'warning'); 30 | return; 31 | } 32 | let data = new FormData(); 33 | let request = new XMLHttpRequest(); 34 | request.responseType = 'json'; 35 | alert_wrapper.innerHTML = ''; 36 | input.disabled = true; 37 | upload_btn.classList.add('d-none'); 38 | loading_btn.classList.remove('d-none'); 39 | cancel_btn.classList.remove('d-none'); 40 | progress_wrapper.classList.remove('d-none'); 41 | let file = input.files[0]; 42 | let filename = file.name; 43 | let filesize = file.size; 44 | document.cookie = `filesize=${filesize}`; 45 | data.append('file', file); 46 | 47 | request.upload.addEventListener('progress', function(e){ 48 | let loaded = e.loaded; 49 | let total = e.total; 50 | let percentage_complete = (loaded / total) * 100; 51 | progress.setAttribute('style', `width: ${Math.floor(percentage_complete)}%`); 52 | progress_status.innerText = `${Math.floor(percentage_complete)}% uploaded`; 53 | }) 54 | 55 | request.addEventListener('load', function(e){ 56 | if(request.status == 200){ 57 | show_alert(`${request.response.message}`, 'success'); 58 | } else { 59 | show_alert(`Error uploading file`, 'danger'); 60 | } 61 | reset(); 62 | }) 63 | 64 | request.addEventListener('error', function(e){ 65 | reset(); 66 | show_alert('Error uploading file', 'danger') 67 | }) 68 | 69 | request.addEventListener('abort', function(e){ 70 | reset(); 71 | show_alert('Uploaded cancelled', 'primary') 72 | }) 73 | 74 | request.open('post', url); 75 | request.send(data); 76 | 77 | cancel_btn.addEventListener('click', function(){ 78 | request.abort(); 79 | }) 80 | 81 | }; 82 | 83 | function reset(){ 84 | input.value = null; 85 | input.disabled = false; 86 | cancel_btn.classList.add('d-none'); 87 | loading_btn.classList.add('d-none'); 88 | upload_btn.classList.remove('d-none'); 89 | progress_wrapper.classList.add('d-none'); 90 | progress.setAttribute('style', 'width: 0%'); 91 | file_input_label.innerText = 'Select File'; 92 | } -------------------------------------------------------------------------------- /Project/app/templates/public/templates/public_template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | {% block title %}{% endblock title %} 12 | 13 | 14 | 49 | 50 |
51 | {% with messages = get_flashed_messages(with_categories=true) %} 52 | {% if messages %} 53 | {% for category, message in messages %} 54 | 60 | {% endfor %} 61 | {% endif %} 62 | {% endwith %} 63 |
64 | 65 |
66 | {% block main %}{% endblock main %} 67 |
68 | 69 | 70 | 71 | 72 | 73 | {% block script %}{% endblock script %} 74 | 75 | -------------------------------------------------------------------------------- /Project/app/templates/public/jinja.html: -------------------------------------------------------------------------------- 1 | {% extends 'public/templates/public_template.html' %} 2 | 3 | {% import 'macros/input_macros.html' as im %} 4 | 5 | {% block title %}Jinja{% endblock title %} 6 | 7 | {% block main %} 8 |
9 |
10 |
11 |

Jinja Template

12 |
13 | 14 |

Variáveis

15 |

Nome: {{ nome }}

16 | 17 |
18 | 19 |

Looping

20 |
    21 | {% for lang in langs %} 22 |
  • {{ lang }}
  • 23 | {% endfor %} 24 |
25 | 26 |
27 | 28 |

Looping with Index

29 |
    30 | {% for lang in langs %} 31 |
  • {{ loop.index }} : {{ lang }}
  • 32 | {% endfor %} 33 |
34 | 35 |
36 | 37 |

Looping Dict

38 |
    39 | {% for k, v in personagens.items() %} 40 |
  • {{ k }} : {{ v }}
  • 41 | {% endfor %} 42 |
43 | 44 |
45 | 46 |

Access List Member

47 |

{{ langs[0] }}

48 | 49 |
50 | 51 |

Access Dict Member

52 |

{{ personagens['Akira'] }}

53 | 54 |
55 | 56 |

Access Class Attributes

57 |

{{ remote.name }}

58 | 59 |
60 | 61 |

Unpack Variables

62 |

{% set a, b, c = cores %}

63 |

{{ a }}

64 |

{{ b }}

65 |

{{ c }}

66 | 67 |
68 | 69 |

Call a Function

70 |

{{ repeat('Flask is Awesome ', 5) }}

71 | 72 |
73 | 74 |

Call a Class Method

75 |

{{ remote.clone() }}

76 | 77 |
78 | 79 |

Conditionals

80 | {% if legal %} 81 |

Legal é verdadeiro

82 | {% endif %} 83 | 84 |
85 | 86 |

Comparisons

87 | {% if idade < 18 %} 88 |

No entry

89 | {% elif idade < 26 %} 90 |

Nearly old enough

91 | {% else %} 92 |

You may enter the door

93 | {% endif %} 94 | 95 |
96 | 97 |

Math

98 |

{{ idade/2 }}

99 | 100 |
101 | 102 |

Template Filters

103 |

{{ langs|length }}

104 |

{{ nome|reverse }}

105 |

{{ nome|upper }}

106 | 107 |
108 | 109 |

Template Filters - join

110 |

{{ langs|join(', ') }}

111 | 112 |
113 | 114 |

Custom Filters

115 |

{{ date|clean_date }}

116 | 117 |
118 | 119 |

Escaping

120 | {{ html }} 121 | {{ html|safe }} 122 | {{ malicioso }} 123 | 124 |
125 | 126 |

Macros

127 | {{ im.input(label='Seu nome', name='name', id='name', placeholder='please enter your name') }} 128 | {{ im.input(label='Sua idade', type='number', name='idade', id='idade', placeholder='please enter your age') }} 129 | {{ im.input(label='Sua senha', type='password', name='password', id='password', placeholder='please enter your password') }} 130 |
131 |
132 |
133 | {% endblock main %} -------------------------------------------------------------------------------- /Project/app/static/client/csv/iris.csv: -------------------------------------------------------------------------------- 1 | sepal_length,sepal_width,petal_length,petal_width,species 2 | 5.1,3.5,1.4,0.2,setosa 3 | 4.9,3.0,1.4,0.2,setosa 4 | 4.7,3.2,1.3,0.2,setosa 5 | 4.6,3.1,1.5,0.2,setosa 6 | 5.0,3.6,1.4,0.2,setosa 7 | 5.4,3.9,1.7,0.4,setosa 8 | 4.6,3.4,1.4,0.3,setosa 9 | 5.0,3.4,1.5,0.2,setosa 10 | 4.4,2.9,1.4,0.2,setosa 11 | 4.9,3.1,1.5,0.1,setosa 12 | 5.4,3.7,1.5,0.2,setosa 13 | 4.8,3.4,1.6,0.2,setosa 14 | 4.8,3.0,1.4,0.1,setosa 15 | 4.3,3.0,1.1,0.1,setosa 16 | 5.8,4.0,1.2,0.2,setosa 17 | 5.7,4.4,1.5,0.4,setosa 18 | 5.4,3.9,1.3,0.4,setosa 19 | 5.1,3.5,1.4,0.3,setosa 20 | 5.7,3.8,1.7,0.3,setosa 21 | 5.1,3.8,1.5,0.3,setosa 22 | 5.4,3.4,1.7,0.2,setosa 23 | 5.1,3.7,1.5,0.4,setosa 24 | 4.6,3.6,1.0,0.2,setosa 25 | 5.1,3.3,1.7,0.5,setosa 26 | 4.8,3.4,1.9,0.2,setosa 27 | 5.0,3.0,1.6,0.2,setosa 28 | 5.0,3.4,1.6,0.4,setosa 29 | 5.2,3.5,1.5,0.2,setosa 30 | 5.2,3.4,1.4,0.2,setosa 31 | 4.7,3.2,1.6,0.2,setosa 32 | 4.8,3.1,1.6,0.2,setosa 33 | 5.4,3.4,1.5,0.4,setosa 34 | 5.2,4.1,1.5,0.1,setosa 35 | 5.5,4.2,1.4,0.2,setosa 36 | 4.9,3.1,1.5,0.1,setosa 37 | 5.0,3.2,1.2,0.2,setosa 38 | 5.5,3.5,1.3,0.2,setosa 39 | 4.9,3.1,1.5,0.1,setosa 40 | 4.4,3.0,1.3,0.2,setosa 41 | 5.1,3.4,1.5,0.2,setosa 42 | 5.0,3.5,1.3,0.3,setosa 43 | 4.5,2.3,1.3,0.3,setosa 44 | 4.4,3.2,1.3,0.2,setosa 45 | 5.0,3.5,1.6,0.6,setosa 46 | 5.1,3.8,1.9,0.4,setosa 47 | 4.8,3.0,1.4,0.3,setosa 48 | 5.1,3.8,1.6,0.2,setosa 49 | 4.6,3.2,1.4,0.2,setosa 50 | 5.3,3.7,1.5,0.2,setosa 51 | 5.0,3.3,1.4,0.2,setosa 52 | 7.0,3.2,4.7,1.4,versicolor 53 | 6.4,3.2,4.5,1.5,versicolor 54 | 6.9,3.1,4.9,1.5,versicolor 55 | 5.5,2.3,4.0,1.3,versicolor 56 | 6.5,2.8,4.6,1.5,versicolor 57 | 5.7,2.8,4.5,1.3,versicolor 58 | 6.3,3.3,4.7,1.6,versicolor 59 | 4.9,2.4,3.3,1.0,versicolor 60 | 6.6,2.9,4.6,1.3,versicolor 61 | 5.2,2.7,3.9,1.4,versicolor 62 | 5.0,2.0,3.5,1.0,versicolor 63 | 5.9,3.0,4.2,1.5,versicolor 64 | 6.0,2.2,4.0,1.0,versicolor 65 | 6.1,2.9,4.7,1.4,versicolor 66 | 5.6,2.9,3.6,1.3,versicolor 67 | 6.7,3.1,4.4,1.4,versicolor 68 | 5.6,3.0,4.5,1.5,versicolor 69 | 5.8,2.7,4.1,1.0,versicolor 70 | 6.2,2.2,4.5,1.5,versicolor 71 | 5.6,2.5,3.9,1.1,versicolor 72 | 5.9,3.2,4.8,1.8,versicolor 73 | 6.1,2.8,4.0,1.3,versicolor 74 | 6.3,2.5,4.9,1.5,versicolor 75 | 6.1,2.8,4.7,1.2,versicolor 76 | 6.4,2.9,4.3,1.3,versicolor 77 | 6.6,3.0,4.4,1.4,versicolor 78 | 6.8,2.8,4.8,1.4,versicolor 79 | 6.7,3.0,5.0,1.7,versicolor 80 | 6.0,2.9,4.5,1.5,versicolor 81 | 5.7,2.6,3.5,1.0,versicolor 82 | 5.5,2.4,3.8,1.1,versicolor 83 | 5.5,2.4,3.7,1.0,versicolor 84 | 5.8,2.7,3.9,1.2,versicolor 85 | 6.0,2.7,5.1,1.6,versicolor 86 | 5.4,3.0,4.5,1.5,versicolor 87 | 6.0,3.4,4.5,1.6,versicolor 88 | 6.7,3.1,4.7,1.5,versicolor 89 | 6.3,2.3,4.4,1.3,versicolor 90 | 5.6,3.0,4.1,1.3,versicolor 91 | 5.5,2.5,4.0,1.3,versicolor 92 | 5.5,2.6,4.4,1.2,versicolor 93 | 6.1,3.0,4.6,1.4,versicolor 94 | 5.8,2.6,4.0,1.2,versicolor 95 | 5.0,2.3,3.3,1.0,versicolor 96 | 5.6,2.7,4.2,1.3,versicolor 97 | 5.7,3.0,4.2,1.2,versicolor 98 | 5.7,2.9,4.2,1.3,versicolor 99 | 6.2,2.9,4.3,1.3,versicolor 100 | 5.1,2.5,3.0,1.1,versicolor 101 | 5.7,2.8,4.1,1.3,versicolor 102 | 6.3,3.3,6.0,2.5,virginica 103 | 5.8,2.7,5.1,1.9,virginica 104 | 7.1,3.0,5.9,2.1,virginica 105 | 6.3,2.9,5.6,1.8,virginica 106 | 6.5,3.0,5.8,2.2,virginica 107 | 7.6,3.0,6.6,2.1,virginica 108 | 4.9,2.5,4.5,1.7,virginica 109 | 7.3,2.9,6.3,1.8,virginica 110 | 6.7,2.5,5.8,1.8,virginica 111 | 7.2,3.6,6.1,2.5,virginica 112 | 6.5,3.2,5.1,2.0,virginica 113 | 6.4,2.7,5.3,1.9,virginica 114 | 6.8,3.0,5.5,2.1,virginica 115 | 5.7,2.5,5.0,2.0,virginica 116 | 5.8,2.8,5.1,2.4,virginica 117 | 6.4,3.2,5.3,2.3,virginica 118 | 6.5,3.0,5.5,1.8,virginica 119 | 7.7,3.8,6.7,2.2,virginica 120 | 7.7,2.6,6.9,2.3,virginica 121 | 6.0,2.2,5.0,1.5,virginica 122 | 6.9,3.2,5.7,2.3,virginica 123 | 5.6,2.8,4.9,2.0,virginica 124 | 7.7,2.8,6.7,2.0,virginica 125 | 6.3,2.7,4.9,1.8,virginica 126 | 6.7,3.3,5.7,2.1,virginica 127 | 7.2,3.2,6.0,1.8,virginica 128 | 6.2,2.8,4.8,1.8,virginica 129 | 6.1,3.0,4.9,1.8,virginica 130 | 6.4,2.8,5.6,2.1,virginica 131 | 7.2,3.0,5.8,1.6,virginica 132 | 7.4,2.8,6.1,1.9,virginica 133 | 7.9,3.8,6.4,2.0,virginica 134 | 6.4,2.8,5.6,2.2,virginica 135 | 6.3,2.8,5.1,1.5,virginica 136 | 6.1,2.6,5.6,1.4,virginica 137 | 7.7,3.0,6.1,2.3,virginica 138 | 6.3,3.4,5.6,2.4,virginica 139 | 6.4,3.1,5.5,1.8,virginica 140 | 6.0,3.0,4.8,1.8,virginica 141 | 6.9,3.1,5.4,2.1,virginica 142 | 6.7,3.1,5.6,2.4,virginica 143 | 6.9,3.1,5.1,2.3,virginica 144 | 5.8,2.7,5.1,1.9,virginica 145 | 6.8,3.2,5.9,2.3,virginica 146 | 6.7,3.3,5.7,2.5,virginica 147 | 6.7,3.0,5.2,2.3,virginica 148 | 6.3,2.5,5.0,1.9,virginica 149 | 6.5,3.0,5.2,2.0,virginica 150 | 6.2,3.4,5.4,2.3,virginica 151 | 5.9,3.0,5.1,1.8,virginica 152 | 153 | -------------------------------------------------------------------------------- /MusicApp/main.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from db_setup import init_db, db_session 3 | from forms import MusicSearchForm, AlbumForm 4 | from flask import flash, render_template, request, redirect 5 | from models import Album, Artist 6 | from tables import Results 7 | 8 | init_db() 9 | 10 | def save_changes(album, form, new=False): 11 | """ 12 | Salva as mudanças no banco de dados 13 | """ 14 | # Obtém dados do formulário e os aloca para os atributos corretos 15 | # do objeto tabela SQLAlchemy 16 | artist = Artist() 17 | artist.name = form.artist.data 18 | 19 | album.artist = artist 20 | album.title = form.title.data 21 | album.release_date = form.release_date.data 22 | album.publisher = form.publisher.data 23 | album.media_type = form.media_type.data 24 | 25 | if new: 26 | # Adiciona o novo álbum ao banco de dados 27 | db_session.add(album) 28 | 29 | # Faz commit dos dados ao banco de dados 30 | db_session.commit() 31 | 32 | @app.route('/', methods=['GET', 'POST']) 33 | def index(): 34 | qry = db_session.query(Album).all() 35 | for q in qry: 36 | print(q.title, q.artist) 37 | search = MusicSearchForm(request.form) 38 | if request.method == 'POST': 39 | return search_results(search) 40 | 41 | return render_template('index.html', form=search, qry=qry) 42 | 43 | @app.route('/results') 44 | def search_results(search): 45 | results = [] 46 | search_string = search.data['search'] 47 | 48 | if search_string: 49 | if search.data['select'] == 'Artist': 50 | qry = db_session.query(Album, Artist).filter( 51 | Artist.id==Album.artist_id).filter( 52 | Artist.name.contains(search_string)) 53 | results = [item[0] for item in qry.all()] 54 | elif search.data['select'] == 'Album': 55 | qry = db_session.query(Album).filter( 56 | Album.title.contains(search_string)) 57 | results = qry.all() 58 | elif search.data['select'] == 'Publisher': 59 | qry = db_session.query(Album).filter( 60 | Album.publisher.contains(search_string)) 61 | results = qry.all() 62 | else: 63 | qry = db_session.query(Album) 64 | results = qry.all() 65 | else: 66 | qry = db_session.query(Album) 67 | results = qry.all() 68 | 69 | if not results: 70 | flash('No results found!') 71 | return redirect('/') 72 | else: 73 | # Apresenta os resultados 74 | table = Results(results) 75 | table.border = True 76 | for result in results: 77 | print(result.title, result.artist) 78 | return render_template('results.html', table=table) 79 | 80 | @app.route('/new_album', methods=['GET', 'POST']) 81 | def new_album(): 82 | """ 83 | Adiciona um novo álbum 84 | """ 85 | form = AlbumForm(request.form) 86 | 87 | if request.method == 'POST' and form.validate(): 88 | # Salva o álbum 89 | album = Album() 90 | save_changes(album, form, new=True) 91 | flash('Album created successfully!') 92 | return redirect('/') 93 | 94 | return render_template('new_album.html', form=form) 95 | 96 | @app.route('/item/', methods=['GET', 'POST']) 97 | def edit(id): 98 | qry = db_session.query(Album).filter(Album.id==id) 99 | album = qry.first() 100 | 101 | if album: 102 | form = AlbumForm(formdata=request.form, obj=album) 103 | if request.method == 'POST' and form.validate(): 104 | # Salva as edições 105 | save_changes(album, form) 106 | flash('Album updated successfully!') 107 | return redirect('/') 108 | return render_template('edit_album.html', form=form) 109 | else: 110 | return 'Error loading #{id}'.format(id=id) 111 | 112 | @app.route('/delete/', methods=['GET', 'POST']) 113 | def delete(id): 114 | """ 115 | Deleta o item no banco de dados que corresponde ao id especificado na URL 116 | """ 117 | qry = db_session.query(Album).filter(Album.id==id) 118 | album = qry.first() 119 | 120 | if album: 121 | form = AlbumForm(formdata=request.form, obj=album) 122 | if request.method == 'POST' and form.validate(): 123 | # Deleta o item do banco de dados 124 | db_session.delete(album) 125 | db_session.commit() 126 | 127 | flash('Album deleted successfully!') 128 | return redirect('/') 129 | return render_template('delete_album.html', form=form) 130 | else: 131 | return 'Error deleting #{id}'.format(id=id) 132 | 133 | if __name__ == '__main__': 134 | app.run(debug=True) -------------------------------------------------------------------------------- /Project/app/views.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flask import render_template, request, redirect, jsonify, make_response, send_from_directory, abort, flash 3 | from datetime import datetime 4 | from werkzeug.utils import secure_filename 5 | import os 6 | 7 | # Criação de Filtro 8 | @app.template_filter('clean_date') 9 | def clean_date(dt): 10 | return dt.strftime('%d %b %Y') 11 | 12 | # Criando uma rota 13 | @app.route('/') 14 | def index(): 15 | return render_template('public/index.html') 16 | 17 | @app.route('/jinja') 18 | def jinja(): 19 | nome = 'Gabriel' 20 | 21 | idade = 28 22 | 23 | langs = ['Python', 'Javascript', 'C', 'C++', 'Bash'] 24 | 25 | personagens = { 26 | 'DBZ': 'Goku', 27 | 'Naruto': 'Kakashi', 28 | 'Death Note': 'Raito Yagami', 29 | 'Akira': 'Tetsuo' 30 | } 31 | 32 | cores = ('red', 'green', 'blue') 33 | 34 | legal = True 35 | 36 | class GitRemote: 37 | def __init__(self, name, description, url): 38 | self.name = name 39 | self.description = description 40 | self.url = url 41 | 42 | def pull(self): 43 | return f'Pulling repo {self.name}' 44 | 45 | def clone(self): 46 | return f'Cloning into {self.url}' 47 | 48 | remote = GitRemote(name='Flask Jinja', description='Template Design Tutorial', url='https://github.com/julian-nash/jinja.git') 49 | 50 | def repeat(x, qty): 51 | return x * qty 52 | 53 | date = datetime.utcnow() 54 | 55 | html = "

Titulo Grande

" 56 | 57 | malicioso = "" 58 | 59 | return render_template( 60 | 'public/jinja.html', 61 | nome=nome, 62 | idade=idade, 63 | langs=langs, 64 | personagens=personagens, 65 | cores=cores, 66 | legal=legal, 67 | GitRemote=GitRemote, 68 | repeat=repeat, 69 | remote=remote, 70 | date=date, 71 | html=html, 72 | malicioso=malicioso 73 | ) 74 | 75 | # Criando uma nova rota about 76 | @app.route('/about') 77 | def about(): 78 | return render_template('public/about.html') 79 | 80 | @app.route('/sign-up', methods=['GET','POST']) 81 | def sign_up(): 82 | if request.method == 'POST': 83 | req = request.form 84 | 85 | username = req['username'] 86 | email = req.get('email') 87 | password = request.form['password'] 88 | 89 | print(username,email,password) 90 | 91 | return redirect(request.url) 92 | 93 | return render_template('public/sign_up.html') 94 | 95 | users = { 96 | 'gabriel': { 97 | 'name': 'Gabriel Felippe', 98 | 'bio': 'Interessado em Computação', 99 | 'twitter': '@akirascientist' 100 | }, 101 | 'akira': { 102 | 'name': 'akira', 103 | 'bio': 'the unknown', 104 | 'twitter': '@akira' 105 | } 106 | } 107 | 108 | @app.route('/profile/') 109 | def profile(username): 110 | 111 | user = None 112 | 113 | if username in users: 114 | user = users[username] 115 | 116 | return render_template('public/profile.html', username=username, user=user) 117 | 118 | @app.route('/multiple///') 119 | def multi(foo, bar, baz): 120 | return f'foo is {foo}, bar is {bar}, baz is {baz}' 121 | 122 | @app.route('/json', methods=['POST']) 123 | def json(): 124 | if request.is_json: 125 | 126 | req = request.get_json() 127 | response = { 128 | "message": "JSON received", 129 | "name": req.get("name") 130 | } 131 | res = make_response(jsonify(response), 200) 132 | 133 | return res 134 | else: 135 | 136 | res = make_response(jsonify({"message": "No JSON received"}), 400) 137 | 138 | return 'No JSON received', 400 139 | 140 | @app.route('/guestbook') 141 | def guestbook(): 142 | return render_template('public/guestbook.html') 143 | 144 | @app.route('/guestbook/create-entry', methods=['POST']) 145 | def create_entry(): 146 | req = request.get_json() 147 | 148 | print(req) 149 | 150 | res = make_response(jsonify(req), 200) 151 | 152 | return res 153 | 154 | @app.route('/query') 155 | def query(): 156 | args = request.args 157 | 158 | for k, v in args.items(): 159 | print(f'{k}:{v}') 160 | 161 | return 'Query received', 200 162 | 163 | app.config['IMAGE_UPLOADS'] = '/home/talantyr/Documentos/Projetos/Python Experimentos/Web Development/Flask/project/app/static/img/uploads' 164 | app.config['ALLOWED_IMAGE_EXTENSIONS'] = ['PNG','JPG','JPEG','GIF'] 165 | app.config['MAX_IMAGE_FILESIZE'] = 0.5 * 1024 * 1024 166 | 167 | def allowed_image(filename): 168 | if not '.' in filename: 169 | return False 170 | ext = filename.rsplit('.',1)[1] 171 | if ext.upper() in app.config['ALLOWED_IMAGE_EXTENSIONS']: 172 | return True 173 | else: 174 | return False 175 | 176 | def allowed_image_file_size(filesize): 177 | if int(filesize) <= app.config['MAX_IMAGE_FILESIZE']: 178 | return True 179 | else: 180 | return False 181 | 182 | @app.route('/upload-image', methods=['GET','POST']) 183 | def upload_image(): 184 | if request.method == 'POST': 185 | if request.files: 186 | if not allowed_image_file_size(request.cookies.get('filesize')): 187 | print('File exceeded maximum size limit') 188 | return redirect(request.url) 189 | image = request.files['image'] 190 | if image.filename == "": 191 | print('Image must have a filename') 192 | return redirect(request.url) 193 | if not allowed_image(image.filename): 194 | print('That image extensions is not allowed') 195 | return redirect(request.url) 196 | else: 197 | filename = secure_filename(image.filename) 198 | image.save(os.path.join(app.config['IMAGE_UPLOADS'], filename)) 199 | print("image saved") 200 | return redirect(request.url) 201 | return render_template('public/upload_image.html') 202 | 203 | """ 204 | string: 205 | int: 206 | float: 207 | path: 208 | uuid: 209 | """ 210 | app.config['CLIENT_IMAGES'] = '/home/talantyr/Documentos/Projetos/Python Experimentos/Web Development/Flask/project/app/static/client/img' 211 | app.config['CLIENT_CSV'] = '/home/talantyr/Documentos/Projetos/Python Experimentos/Web Development/Flask/project/app/static/client/csv' 212 | app.config['CLIENT_REPORTS'] = '/home/talantyr/Documentos/Projetos/Python Experimentos/Web Development/Flask/project/app/static/client/reports' 213 | @app.route('/get-image/') 214 | def get_image(image_name): 215 | try: 216 | return send_from_directory(app.config['CLIENT_IMAGES'], filename=image_name, as_attachment=False) 217 | except FileNotFoundError: 218 | abort(404) 219 | 220 | @app.route('/get-csv/') 221 | def get_csv(filename): 222 | try: 223 | return send_from_directory(app.config['CLIENT_CSV'], filename=filename, as_attachment=True) 224 | except FileNotFoundError: 225 | abort(404) 226 | 227 | @app.route('/get-report/') 228 | def get_report(path): 229 | try: 230 | return send_from_directory(app.config['CLIENT_REPORTS'], filename=path, as_attachment=True) 231 | except FileNotFoundError: 232 | abort(404) 233 | 234 | @app.route('/cookies') 235 | def cookies(): 236 | res = make_response('Cookies', 200) 237 | cookies = request.cookies 238 | sabor = cookies.get('sabor') 239 | print(sabor) 240 | res.set_cookie('sabor', value='pizza', max_age=10, expires=None, path=request.path, domain=None, secure=False, httponly=False, samesite=False) 241 | return res 242 | 243 | @app.route('/signup', methods=['GET','POST']) 244 | def signup(): 245 | if request.method == 'POST': 246 | req = request.form 247 | username = req.get('username') 248 | email = req.get('email') 249 | password = req.get('password') 250 | 251 | if not len(password) >= 10: 252 | flash('Password must bet at least 10 characters in length','warning') 253 | return redirect(request.url) 254 | 255 | flash('Account created','success') 256 | 257 | return redirect(request.url) 258 | return render_template('public/signup.html') --------------------------------------------------------------------------------