forked from Danilo-Miguel/PythonWeb-13-03
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
65 lines (52 loc) · 1.79 KB
/
app.py
1
2
3
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from flask import Flask, render_template, g, request, redirect, session, url_for, flash, abort
import sqlite3
app = Flask("blog")
DATABASE = "banco.bd"
SECRET_KEY = "1234"
app.config.from_object(__name__)
def conectar():
return sqlite3.connect(DATABASE)
@app.before_request
def before_request():
g.bd = conectar()
@app.teardown_request
def teardown_request(f):
g.bd.close()
@app.route("/")
def exibir_posts():
sql = "SELECT titulo, texto, data_criacao FROM posts ORDER BY id DESC"
resultado = g.bd.execute(sql)
post = []
for titulo, texto, data_criacao in resultado.fetchall():
post.append({
"titulo":titulo,
"texto":texto,
"data_criacao":data_criacao
})
return render_template("exibir_posts.html", post=post)
@app.route("/inserir", methods= ["POST", "GET"])
def inserir():
if not session.get('logado'):
abort(401)
titulo = request.form.get('titulo')
texto = request.form.get('texto')
sql = "INSERT INTO posts (titulo, texto) VALUES (?, ?)"
g.bd.execute(sql,[titulo, texto])
g.bd.commit()
flash("Novo post inserido")
return redirect(url_for('exibir_posts'))
@app.route("/login", methods= ["POST", "GET"])
def login():
erro = None
if(request.method == "POST"):
if request.form['username'] == "Ocean" and request.form['password'] == "ocean1234":
session['logado'] = True
flash("Usuário logado com sucesso!" + request.form['username'])
return redirect(url_for('exibir_posts'))
erro="Usuário ou senha incorretos"
return render_template("login.html", erro=erro)
@app.route("/logout")
def logout():
session.pop('logado', None)
flash("Logout efetuado com sucesso")
return redirect(url_for('exibir_posts'))