Commit 1855b6d6 authored by Давид Ли's avatar Давид Ли

lesson 39

parent 1fcad6e3
from .base import BaseController
from app.db import Database
class PostsController(BaseController):
def get_list(self):
body = '<h1>This is our posts</h1>'
for post in Database.posts:
body += f'<h3>{post["id"]} - {post["title"]}'
self.response.add_header('Content-Type', 'text/html')
self.response.set_body(body)
def create_post(self):
if self.request.method == 'GET':
with open('static/create_post_form.html', 'r') as f:
body = f.read()
self.response.add_header('Content-Type', 'text/html')
self.response.set_body(body)
else:
print(777, self.request.body)
post = {
'id': Database.posts[-1]['id'] + 1,
'title': self.request.body['title'][0],
'description': self.request.body['description'][0],
}
Database.add(post)
self.response.set_status(301)
self.response.add_header('Location', '/posts')
class Database:
posts = [
{
'id': 1,
'title': 'This is my first post!',
'description': 'This is test description',
},
{
'id': 2,
'title': 'This is my second post!',
'description': 'This is second test description',
},
]
@classmethod
def add(cls, post):
cls.posts.append(post)
\ No newline at end of file
from .base import BaseController
class PostsController(BaseController):
def get_list(self):
posts_bd = [
{'id': 1, 'title': 'This is 1st post'},
{'id': 2, 'title': 'This is 2st post'},
{'id': 3, 'title': 'This is 3st post'},
]
body = '<h1>This is our posts</h1>'
for post in posts_bd:
body += f'<h3>{post["id"]} - {post["title"]}'
self.response.add_header('Content-Type', 'text/html')
self.response.set_body(body)
from response import Response from .response import Response
from request import Request from .request import Request
def not_found(request, response): def not_found(request, response):
......
from urllib.parse import parse_qs
class Request: class Request:
def __init__(self, rfile): def __init__(self, rfile):
self.file = rfile self.file = rfile
...@@ -16,6 +19,8 @@ class Request: ...@@ -16,6 +19,8 @@ class Request:
request_line = self.__readline() request_line = self.__readline()
# GET / HTTP/1.1 ['GET', '/', 'HTTP/1.1'] # GET / HTTP/1.1 ['GET', '/', 'HTTP/1.1']
print(request_line.split())
self.method, self.uri, self.protocol = request_line.split() self.method, self.uri, self.protocol = request_line.split()
def __readline(self): def __readline(self):
...@@ -31,10 +36,15 @@ class Request: ...@@ -31,10 +36,15 @@ class Request:
name, value = header.split(': ') name, value = header.split(': ')
self.headers[name] = value self.headers[name] = value
def __parse_specific_body(self):
if self.headers['Content-Type'] == 'application/x-www-form-urlencoded':
self.body = parse_qs(self.body)
def __parse_body(self): def __parse_body(self):
if 'Content-Length' in self.headers: if 'Content-Length' in self.headers:
content_length = int(self.headers['Content-Length']) content_length = int(self.headers['Content-Length'])
self.body = self.file.read(content_length) self.body = self.file.read(content_length).decode()
self.__parse_specific_body()
def __str__(self): def __str__(self):
return ( return (
......
...@@ -6,12 +6,14 @@ class Response: ...@@ -6,12 +6,14 @@ class Response:
HTTP_BAD_REQUEST = 400 HTTP_BAD_REQUEST = 400
HTTP_NOT_FOUND = 404 HTTP_NOT_FOUND = 404
HTTP_INTERNAL_SERVER_ERROR = 500 HTTP_INTERNAL_SERVER_ERROR = 500
HTTP_MOVED_PERMANENTLY = 301
MESSAGES = { MESSAGES = {
HTTP_OK: 'OK', HTTP_OK: 'OK',
HTTP_BAD_REQUEST: 'Bad Request', HTTP_BAD_REQUEST: 'Bad Request',
HTTP_NOT_FOUND: 'Not Found', HTTP_NOT_FOUND: 'Not Found',
HTTP_INTERNAL_SERVER_ERROR: 'Internal Server Error' HTTP_INTERNAL_SERVER_ERROR: 'Internal Server Error',
HTTP_MOVED_PERMANENTLY: 'Moved Permanently',
} }
PROTOCOL = 'HTTP/1.1' PROTOCOL = 'HTTP/1.1'
......
# router = Router() from .errors import not_found, internal_server_error
#
# router.get('/', PagesController, 'home')
#
# router.post('/posts', PostController, 'create')
#
# router.run()
from errors import not_found, internal_server_error
class Router: class Router:
...@@ -42,5 +34,6 @@ class Router: ...@@ -42,5 +34,6 @@ class Router:
try: try:
ctrl = route['ctrl'](request, response) ctrl = route['ctrl'](request, response)
getattr(ctrl, route['ctrl_method'])() getattr(ctrl, route['ctrl_method'])()
except BaseException: except BaseException as e:
print(e)
return internal_server_error(request, response) return internal_server_error(request, response)
from http_fw.request import Request
from http_fw.response import Response
from http_fw.static_responder import StaticResponder
import socketserver
#REST RESTfull
#CRUDL - Create, Read, Update, Delete, List
#/posts
#GET - /posts
#GET - /posts/{id}
#POST - /posts
#PUT\PATH - /posts/{id}
#DELETE - /posts/{id}
def run(router):
class Handler(socketserver.StreamRequestHandler):
def handle(self):
request = Request(self.rfile)
response = Response(self.wfile)
response.add_header('Connection', 'close')
static_responder = StaticResponder(request, response)
print(request)
if static_responder.file:
static_responder.prepare_response()
else:
router.run(request, response)
response.send()
ADDRESS = ('localhost', 1027)
socketserver.ThreadingTCPServer.allow_reuse_address = True
with socketserver.ThreadingTCPServer(ADDRESS, Handler) as server:
server.serve_forever()
from request import Request
from response import Response
import errors
from static_responder import StaticResponder
import socketserver
from controllers.pages import PagesController
from controllers.posts import PostsController
from errors import not_found
from errors import not_found
from router import Router
#REST RESTfull
#CRUDL - Create, Read, Update, Delete, List
#/posts
#GET - /posts
#GET - /posts/{id}
#POST - /posts
#PUT\PATH - /posts/{id}
#DELETE - /posts/{id}
router = Router()
router.get('/', PagesController, 'home')
router.get('/about', PagesController, 'about')
router.get('/posts', PostsController, 'get_list')
class Handler(socketserver.StreamRequestHandler):
# self.request - client socket
def handle(self):
request = Request(self.rfile)
response = Response(self.wfile)
response.add_header('Connection', 'close')
# static_responder = StaticResponder(request, response)
print(request)
router.run(request, response)
response.send()
ADDRESS = ('localhost', 1027)
socketserver.ThreadingTCPServer.allow_reuse_address = True
with socketserver.ThreadingTCPServer(ADDRESS, Handler) as server:
server.serve_forever()
from app.controllers.pages import PagesController
from app.controllers.posts import PostsController
from http_fw.server import run
from http_fw.router import Router
router = Router()
router.get('/', PagesController, 'home')
router.get('/about', PagesController, 'about')
router.get('/posts', PostsController, 'get_list')
router.get('/posts/new', PostsController, 'create_post')
router.post('/posts', PostsController, 'create_post')
run(router)
<form action="/posts" method="POST">
<h1>Create new post!</h1>
<label>
Title: <input type="text" name="title" />
</label>
<br/>
<label>
Description: <textarea name="description"></textarea>
</label>
<br/>
<input type="submit" value="Create!"/>
<br/>
<a href="/">Return to main page</a>
</form>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment