Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hw8 #105

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open

Hw8 #105

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
27 changes: 22 additions & 5 deletions resources/session02/homework/http_server.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import socket
import sys
import os
import mimetypes


def response_ok(body=b"this is a pretty minimal response", mimetype=b"text/plain"):
"""returns a basic HTTP response"""
resp = []
resp.append(b"HTTP/1.1 200 OK")
resp.append(b"Content-Type: text/plain")
resp.append(b"Content-Type: " + mimetype)
resp.append(b"")
resp.append(b"this is a pretty minimal response")
resp.append(body)
return b"\r\n".join(resp)


Expand All @@ -22,7 +24,10 @@ def response_method_not_allowed():

def response_not_found():
"""returns a 404 Not Found response"""
return b""
resp = []
resp.append("HTTP/1.1 404 Not Found")
resp.append("")
return "\r\n".join(resp).encode('utf8')


def parse_request(request):
Expand All @@ -35,15 +40,27 @@ def parse_request(request):

def resolve_uri(uri):
"""This method should return appropriate content and a mime type"""
return b"still broken", b"text/plain"
home = os.getcwd() + "/webroot"
path = home + uri
if os.path.isfile(path):
mime, encoding = mimetypes.guess_type(path)
with open(path, 'rb') as f:
content = f.read()
elif os.path.isdir(path):
mime = "text/plain"
files = os.listdir(path)
content = "\n".join(files).encode('utf8')
else:
raise NameError
return content, mime.encode('utf8')


def server(log_buffer=sys.stderr):
address = ('127.0.0.1', 10000)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("making a server on {0}:{1}".format(*address), file=log_buffer)
sock.bind(address)
sock.bind(address)
sock.listen(1)

try:
Expand Down
66 changes: 66 additions & 0 deletions resources/session03/wsgi/calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import re


def resolve_path(path):
urls = [(r'^$', welcome),
(r'^add/(\d+)/(\d+)$', add),
(r'^subtract/(\d+)/(\d+)$', subtract),
(r'^divide/(\d+)/(\d+)$', divide),
(r'^multiply/(\d+)/(\d+)$', multiply)]

matchpath = path.lstrip('/')
for regexp, func in urls:
match = re.match(regexp, matchpath)
if match is None:
continue
args = match.groups([])
return func, args
# we get here if no url matches
raise NameError

def welcome():
return "<h1>welcome</h1>"

def multiply(v1, v2):
r = int(v1) * int(v2)
return "<h1>result from multiplication: %d</h1>" %r

def add(v1, v2):
r = int(v1) + int(v2)
return "<h1>result from addition: %d</h1>" % r

def subtract(v1, v2):
r = int(v1) - int(v2)
return "<h1>result from subtraction: %d</h1>" % r

def divide(v1, v2):
r = int(v1) / int(v2)
return "<h1>result from division: %d</h1>" % r

def application(environ, start_response):
headers = [("Content-type", "text/html")]
try:
path = environ.get('PATH_INFO', None)
if path is None:
raise NameError
func, args = resolve_path(path)
body = func(*args)
status = "200 OK"
except NameError:
status = "404 Not Found"
body = "<h1>Not Found</h1>"
except ZeroDivisionError:
status = "400 Bad Request"
body = "<h1>Bad Request</h1>"
except Exception:
status = "500 Internal Server Error"
body = "<h1>Internal Server Error</h1>"
finally:
headers.append(('Content-length', str(len(body))))
start_response(status, headers)
return [body.encode('utf8')]

if __name__ == '__main__':
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()
16 changes: 14 additions & 2 deletions resources/session08/mysite_stage_3/myblog/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,17 @@
from myblog.models import Post


admin.site.register(Category)
admin.site.register(Post)
class CategoryInline(admin.TabularInline):
model = Category.posts.through

class PostAdmin(admin.ModelAdmin):
inlines = [
CategoryInline,
]

class CategoryAdmin(admin.ModelAdmin):
exclude = ('posts', )


admin.site.register(Category, CategoryAdmin)
admin.site.register(Post, PostAdmin)
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends "base.html" %}

{% block content %}
<h1>My Blog Registration form</h1>
<form action="" method="POST">{% csrf_token %}
{{ form.as_p }}
<p><input type="submit" value="Register"></p>
</form>
{% endblock %}

3 changes: 2 additions & 1 deletion resources/session08/mysite_stage_3/myblog/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.conf.urls import url
from django.conf.urls import include, url

from myblog.views import stub_view
from myblog.views import list_view
Expand All @@ -12,4 +12,5 @@
url(r'^posts/(?P<post_id>\d+)/$',
detail_view,
name='blog_detail'),
url(r'^accounts/', include('registration.backends.simple.urls')),
]