Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import http.server
- import socketserver
- import time
- # port serwera
- PORT = 8000
- # dziedziczymy po klasie handlera bazowego
- class MyHandler(http.server.BaseHTTPRequestHandler):
- def do_HEAD(self):
- ''' metoda obsługuje zapytania HEAD'''
- self.send_response(200)
- self.send_header("Content-type", "text/html")
- self.end_headers()
- def do_GET(self):
- ''' metoda obsługuje zapytania GET '''
- print('przyszło zapytanie:', self.path)
- # rozwiązywanie zapytania
- if self.path == '/' or self.path.endswith('index.html'):
- # wysyłanie nagłówka
- self.send_response(200)
- self.send_header("Content-type", "text/html")
- self.end_headers()
- content = '''
- <html>
- <head>
- <title>zegar</title>
- <link rel="stylesheet" type="text/css" href="style.css">
- <head>
- <body>
- <div>zegar: %s</div>
- <script src="script.js"></script>
- </body>
- </html>'''
- # wstawianie stringa
- content %= time.strftime('%H:%M:%S')
- # wysyłanie zawartości strony
- self.wfile.write(bytes(content, 'utf-8'))
- # wyjście z metody (żeby dalszy kod się nie wykonywał
- return
- # obsługa np. cssów
- if self.path.endswith('.css'):
- self.send_response(200)
- # content type jest inny
- self.send_header("Content-type", "text/css")
- self.end_headers()
- # otwieranie pliku w trybie binarnym
- with open('.' + self.path, 'rb') as f:
- self.wfile.write(f.read())
- return
- # obsługa javascript
- if self.path.endswith('.js'):
- self.send_response(200)
- # content type jest inny
- self.send_header("Content-type", "application/javascript")
- self.end_headers()
- # otwieranie pliku w trybie binarnym
- with open('.' + self.path, 'rb') as f:
- self.wfile.write(f.read())
- return
- # analogicznie inne typy plików
- # w przypadku błędów
- self.send_error(404, 'Strona nieodnaleziona')
- def main():
- handler = MyHandler
- address = ('', PORT)
- s = socketserver.TCPServer(address, handler)
- print('serwer nasłuchuje na porcie:', PORT)
- s.serve_forever()
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement