forked from Attakay78/Episode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·79 lines (62 loc) · 2.53 KB
/
main.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#! /usr/bin/python3
from episode.episode import Episode
from episode.httpresponse import HttpResponse
from episode.httpstatus import HTTPStatus
from episode.sqlmodel import Model, Session, DBType, DBConnection
from episode.template_engine import render_template
file_path = "student_db.sqlite"
db_conn = DBConnection.dialect(DBType.SQLITE)
connection = db_conn(database_path=file_path)
class Student(Model):
first_name: str
last_name: str
user_name: str
age: int
with Session(connection) as session:
session.delete_and_create(Student)
if __name__ == "__main__":
episode = Episode()
# Expecting a get request only with path parameter 'username'
@episode.get("/students/{username}")
def get_student_by_username(request, username: str):
with Session(connection) as session:
sql_stmt = session.select(Student).where(Student.user_name == username)
students = list(session.exec(sql_stmt))
student = students[0] if students else None
if student:
context = {
"first_name": student.first_name,
"last_name": student.last_name,
"age": student.age,
}
return render_template("student.html", context=context)
else:
return HttpResponse().write(
f"Student with username {username} does not exist",
status_code=HTTPStatus.NOT_FOUND,
)
# Expecting a post request only
@episode.post("/students/add/")
def add_student(request, student: Student):
with Session(connection) as session:
sql_smt = session.select(Student).where(Student.user_name == student.user_name)
students = list(session.exec(sql_smt))
if students:
return HttpResponse().write(
f"User with username {student.user_name} already exist",
status_code=HTTPStatus.BAD_REQUEST,
)
session.save(student)
return HttpResponse().write(
"Data stored successfully", status_code=HTTPStatus.CREATED
)
# Expecting path parameter 'id' and a query parameter 'a'
@episode.route("/index/{id}/")
def get_hello(request, id, a: int):
return HttpResponse().write(f"Hello world {id}")
@episode.get("/index/")
def get_hello(request):
return render_template(
"index.html", context={"topics": ["Python", "Golang", "Java", "C++"]}
)
episode.start()