Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"livePreview.defaultPreviewPath": "/exemplos/day1/pagina.html"
}
Binary file added exemplos/day1/blog/blog.db
Binary file not shown.
54 changes: 54 additions & 0 deletions exemplos/day1/blog/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 1 - conectamos ao banco de dados
from sqlite3 import connect

conn = connect("blog.db")
cursor = conn.cursor()

# 2 - Criamos a tabela caso não exista
conn.execute(
"""\
CREATE TABLE if not exists post (
id integer PRIMARY KEY AUTOINCREMENT,
title varchar UNIQUE NOT NULL,
content varchar NOT NULL,
author varchar NOT NULL
);
"""
)

# 3 - Criamos os posts iniciais para alimentar o banco de dados
posts = [
{
"title": "Python é eleita a linguagem mais popular",
"content": """\
A linguem Python foi eleita a linguagem mais popular pela revista
tech masters e segue dominando o mundo.
""",
"author": "Satoshi Namamoto",
},
{
"title": "Como criar um blog utilizando Python",
"content": """\
Neste tutorial você aprenderá como criar um blog utilizando Python.
<pre> import make_a_blog </pre>
""",
"author": "Guido Van Rossum",
},
]


# 4 - Inserimos os posts caso o banco de dados esteja vazio
count = cursor.execute("SELECT * FROM post;").fetchall()
if not count:
cursor.executemany(
"""\
INSERT INTO post (title, content, author)
VALUES (:title, :content, :author);
""",
posts,
)
conn.commit()

# 5 - Verificamos que foi realmente inserido
posts = cursor.execute("SELECT * FROM post;").fetchall()
assert len(posts) >= 2
19 changes: 19 additions & 0 deletions exemplos/day1/blog/form.template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>New Post</h1>
<form action="/new" method="post">
<label for="title">Title:</label><br>
<input type="text" name="title" /><br>
<label for="content">Content:</label><br>
<textarea name="content" cols="30" rows="5"></textarea><br>
<label for="author">Author:</label><br>
<input type="text" name="author" /><br>
<input type="submit" value="Enviar">
</form>
</body>
</html>
13 changes: 13 additions & 0 deletions exemplos/day1/blog/list.template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Blog Posts:</h1>
<ul>
{post_list}
</ul>
</body>
</html>
16 changes: 16 additions & 0 deletions exemplos/day1/blog/post.template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>{post[title]}</h1>
<hr />
<p>
{post[content]}
</p>
<hr />
<small>{post[author]}</small>
</body>
</html>
38 changes: 38 additions & 0 deletions exemplos/day1/blog/render.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from pathlib import Path
from database import conn

# 1 - Obtemos os posts do banco de dados e deserializamos em um dict
cursor = conn.cursor()
fields = ("id", "title", "content", "author")
results = cursor.execute("SELECT * FROM post;")
posts = [dict(zip(fields, post)) for post in results]

# 2 - Criamos a pasta de destino do site
site_dir = Path("site")
site_dir.mkdir(exist_ok=True)

# 3 - Criamos uma função capaz de gerar a url de um post
def get_post_url(post):
slug = post["title"].lower().replace(" ", "-")
return f"{slug}.html"


# 3 - Renderizamos o a página `index.html` a partir do template.
index_template = Path("list.template.html").read_text()
index_page = site_dir / Path("index.html")
post_list = [
f"<li><a href='{get_post_url(post)}'>{post['title']}</a></li>"
for post in posts
]
index_page.write_text(index_template.format(post_list="\n".join(post_list)))

# 4 - Renderizamos todas as páginas para cada post partir do template.
for post in posts:
post_template = Path("post.template.html").read_text()
post_page = site_dir / Path(get_post_url(post))
post_page.write_text(post_template.format(post=post))

print("Site generated at", site_dir)

# 5 - fechamos a conexão
conn.close()
18 changes: 18 additions & 0 deletions exemplos/day1/blog/site/como-criar-um-blog-utilizando-python..html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Como criar um blog utilizando Python.</h1>
<hr />
<p>
Neste tutorial você aprenderá como criar um blog utilizando Python.
<pre> import make_a_blog </pre>

</p>
<hr />
<small>Guido Van Rossum</small>
</body>
</html>
14 changes: 14 additions & 0 deletions exemplos/day1/blog/site/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Blog Posts:</h1>
<ul>
<li><a href='python-é-eleita-a-linguagem-mais-popular..html'>Python é eleita a linguagem mais popular.</a></li>
<li><a href='como-criar-um-blog-utilizando-python..html'>Como criar um blog utilizando Python.</a></li>
</ul>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Python é eleita a linguagem mais popular.</h1>
<hr />
<p>
A linguem Python foi eleita a linguagem mais popular pela revista
tech masters e segue dominando o mundo.

</p>
<hr />
<small>Satoshi Namamoto</small>
</body>
</html>
86 changes: 86 additions & 0 deletions exemplos/day1/blog/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import cgi
from pathlib import Path
from database import conn


def add_new_post(post):
cursor = conn.cursor()
cursor.execute(
"""\
INSERT INTO post (title, content, author)
VALUES (:title, :content, :author);
""",
post,
)
conn.commit()


def render_template(template_name, **context):
template = Path(template_name).read_text()
return template.format(**context).encode("utf-8")


def get_posts_from_database(post_id=None):
cursor = conn.cursor()
fields = ("id", "title", "content", "author")

if post_id:
results = cursor.execute("SELECT * FROM post WHERE id = ?;", post_id)
else:
results = cursor.execute("SELECT * FROM post;")

return [dict(zip(fields, post)) for post in results]


def get_post_list(posts):
post_list = [
f"""<li><a href="/{post['id']}">{post['title']}</a></li>"""
for post in posts
]
return "\n".join(post_list)


def application(environ, start_response):
path = environ["PATH_INFO"]
method = environ["REQUEST_METHOD"]
body = b"Content Not Found"
status = "404 Not Found"

if path == "/" and method == "GET":
posts = get_posts_from_database()
body = render_template(
"list.template.html", post_list=get_post_list(posts)
)
status = "200 OK"

elif path.split("/")[-1].isdigit() and method == "GET":
post_id = path.split("/")[-1]
body = render_template(
"post.template.html",
post=get_posts_from_database(post_id=post_id)[0],
)
status = "200 OK"

elif path == "/new" and method == "POST":
form = cgi.FieldStorage(
fp=environ["wsgi.input"], environ=environ, keep_blank_values=1
)
post = {item.name: item.value for item in form.list}
add_new_post(post)
body = b"New post Created with Success!"
status = "201 Created"

elif path == "/new" and method == "GET":
body = render_template("form.template.html")
status = "200 OK"

headers = [("Content-type", "text/html")]
start_response(status, headers)
return [body]


if __name__ == "__main__":
from wsgiref.simple_server import make_server

server = make_server("0.0.0.0", 8000, application)
server.serve_forever()
Binary file added exemplos/day1/blog_framework/blog.db
Binary file not shown.
54 changes: 54 additions & 0 deletions exemplos/day1/blog_framework/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 1 - conectamos ao banco de dados
from sqlite3 import connect

conn = connect("blog.db")
cursor = conn.cursor()

# 2 - Criamos a tabela caso não exista
conn.execute(
"""\
CREATE TABLE if not exists post (
id integer PRIMARY KEY AUTOINCREMENT,
title varchar UNIQUE NOT NULL,
content varchar NOT NULL,
author varchar NOT NULL
);
"""
)

# 3 - Criamos os posts iniciais para alimentar o banco de dados
posts = [
{
"title": "Python é eleita a linguagem mais popular",
"content": """\
A linguem Python foi eleita a linguagem mais popular pela revista
tech masters e segue dominando o mundo.
""",
"author": "Satoshi Namamoto",
},
{
"title": "Como criar um blog utilizando Python",
"content": """\
Neste tutorial você aprenderá como criar um blog utilizando Python.
<pre> import make_a_blog </pre>
""",
"author": "Guido Van Rossum",
},
]


# 4 - Inserimos os posts caso o banco de dados esteja vazio
count = cursor.execute("SELECT * FROM post;").fetchall()
if not count:
cursor.executemany(
"""\
INSERT INTO post (title, content, author)
VALUES (:title, :content, :author);
""",
posts,
)
conn.commit()

# 5 - Verificamos que foi realmente inserido
posts = cursor.execute("SELECT * FROM post;").fetchall()
assert len(posts) >= 2
Loading