Skip to content

Commit 41f3aa5

Browse files
committed
创建项目
1 parent 25fe2e4 commit 41f3aa5

16 files changed

+362
-0
lines changed

autumn-mvc/__init__.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from .config import config # NOQA
2+
from .base import application as autumn # NOQA
3+
from .base import controller # NOQA
4+
from .base import content_type # NOQA

autumn-mvc/base/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .application import application # NOQA
2+
from .controller import controller # NOQA
3+
from .controller import content_type # NOQA

autumn-mvc/base/application.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from wsgiref.simple_server import make_server
2+
from .. import config
3+
from .guid import guid
4+
import sys
5+
import os
6+
7+
8+
class context:
9+
def __init__(self, environ, write):
10+
self.environ = environ
11+
self.write = write
12+
self.messages = None
13+
14+
15+
class application:
16+
def __init__(self):
17+
self.app = None
18+
self.middlewares = []
19+
self.guid = guid
20+
21+
def start(self):
22+
self._print_info()
23+
sys.path.insert(0, config["middleware"]["path"])
24+
for middleware in config["middleware"]["list"]:
25+
self.middleware(getattr(__import__(middleware), middleware)) # NOQA
26+
make_server('', config["port"], self._run).serve_forever()
27+
28+
def middleware(self, middleware):
29+
self.middlewares.append(middleware)
30+
31+
def _print_info(self):
32+
print("---------------------------------------------------")
33+
print(" port | {port} ".format(port=config["port"]))
34+
print(" url | http://localhost:{port} ".format(port=config["port"]))
35+
print(" path | {path} ".format(path=os.getcwd()))
36+
print("---------------------------------------------------")
37+
38+
def _run(self, environ, start_response):
39+
request = context(environ, None)
40+
response = context(environ, start_response)
41+
for middleware in self.middlewares:
42+
if not middleware(self, request, response, config):
43+
break
44+
return response.messages

autumn-mvc/base/controller.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import pickle
2+
3+
4+
class content_type:
5+
html = 1
6+
json = 2
7+
string = 3
8+
9+
10+
class controller:
11+
def __init__(self):
12+
self.config = {}
13+
self.request = None
14+
self.response = None
15+
16+
def html(self, input):
17+
return {
18+
"template": input,
19+
"type": content_type.html
20+
}
21+
22+
def view(self):
23+
path = self.config["view"]["path"] # NOQA
24+
action = self.request.router.action # NOQA
25+
suffix = self.config["view"]["suffix"] # NOQA
26+
file = "{path}/{action}.{suffix}".format(**locals())
27+
template = None
28+
with open(file, 'r') as f:
29+
template = f.read()
30+
return self.html(template)
31+
32+
def json(self, input):
33+
return {
34+
"template": str(pickle.dumps(input)),
35+
"type": content_type.json
36+
}
37+
38+
def assign(self, key, value):
39+
if not hasattr(self.response, "views"):
40+
self.response.views = {}
41+
self.response.views[key] = value
42+
43+
@property
44+
def cookie(self):
45+
return self.response.cookie
46+
47+
@property
48+
def session(self):
49+
return self.response.session

autumn-mvc/base/guid.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import threading
2+
import os
3+
import uuid
4+
5+
6+
def guid():
7+
def get_mac_address():
8+
node = uuid.getnode()
9+
return uuid.UUID(int=node).hex[-12:]
10+
threadId = threading.currentThread().ident
11+
processId = os.getpid()
12+
mac = get_mac_address()
13+
random = list("{threadId}{processId}{mac}".format(**locals()))[0:32] # NOQA
14+
random.insert(19, "-")
15+
random.insert(15, "-")
16+
random.insert(11, "-")
17+
random.insert(7, '-')
18+
return "".join(random)

autumn-mvc/config/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .config import config # NOQA

autumn-mvc/config/config.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import os
2+
3+
config = {
4+
# Web应用端口
5+
"port": 3055,
6+
"middleware": {
7+
# 框架内置中间件
8+
"list": [
9+
"http_middleware",
10+
"static_middleware",
11+
"cookie_middleware",
12+
"session_middleware",
13+
"router_middleware",
14+
"mvc_middleware",
15+
"template_middleware",
16+
"response_middleware"],
17+
# 中间件目录
18+
"path": "{path}/../middleware".format(path=os.path.dirname(os.path.realpath(__file__))), # NOQA
19+
},
20+
"controller": {
21+
# 控制器目录
22+
"path": "{path}/controller".format(path=os.getcwd())
23+
},
24+
"router": {
25+
# 路由模式
26+
"model": 1,
27+
# 默认控制器
28+
"controller": "home",
29+
# 默认action
30+
"action": "index"
31+
},
32+
"view": {
33+
# 视图目录
34+
"path": "{path}/view".format(path=os.getcwd()),
35+
# 视图后缀名
36+
"suffix": "html"
37+
},
38+
"static": {
39+
# 静态文件后缀名
40+
"suffix": ["html", "jpg", "ico", "png", "css", "json", "js", "gif", "txt"], # NOQA
41+
# 静态文件路径
42+
"path": "{path}/static".format(path=os.getcwd()),
43+
},
44+
"session": {
45+
"id": "autumn_session_id"
46+
}
47+
}
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
def cookie_middleware(app, request, response, config):
2+
request.cookie = cookies()
3+
if "HTTP_COOKIE" in request.environ:
4+
for cookie in request.environ["HTTP_COOKIE"].split(";"):
5+
key = cookie.split("=")[0]
6+
value = cookie.split("=")[1]
7+
setattr(request.cookie, key, value)
8+
9+
def set_cookie(key, value):
10+
if "Set-Cookie" not in response.heads:
11+
response.heads["Set-Cookie"] = u"{key}={value};".format(**locals())
12+
else:
13+
response.heads["Set-Cookie"] += u";{key}={value}".format(**locals())
14+
15+
response.cookie = cookies(set_cookie) # NOQA)
16+
return True
17+
18+
19+
class cookies:
20+
def __init__(self, set_cooie=None):
21+
if set_cooie:
22+
self.__dict__["set_cooie"] = set_cooie
23+
24+
def __setattr__(self, key, value):
25+
print(key)
26+
self.__dict__[key] = value
27+
if "set_cooie" in self.__dict__ and key != "set_cookie":
28+
self.__dict__["set_cooie"](key, value)
29+
30+
def __getattr__(self, key):
31+
if key not in self.__dict__:
32+
return None
33+
return self.__dict__[key]
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def http_middleware(app, request, response, config):
2+
# 设置 web url
3+
if 'PATH_INFO' in request.environ:
4+
request.url = response.url = request.environ["PATH_INFO"]
5+
else:
6+
request.url = response.url = ""
7+
8+
# 设置响应函数
9+
def send(message):
10+
html = message.encode("utf-8") if type(message) == str else message
11+
if not response.messages:
12+
response.messages = [html]
13+
else:
14+
response.messages.append(html)
15+
response.send = send
16+
17+
# 状态码
18+
response.status = 200
19+
20+
# 设置响应头
21+
response.heads = {}
22+
23+
return True
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import sys
2+
3+
content_types = {
4+
1: "text/html",
5+
2: "application/json"
6+
}
7+
8+
9+
def mvc_middleware(app, request, response, config):
10+
# 获取controller
11+
if request.router.controller:
12+
sys.path.insert(0, config["controller"]["path"])
13+
controller = getattr(__import__(request.router.controller), request.router.controller)() # NOQA
14+
controller.request = request
15+
controller.response = response
16+
controller.config = config
17+
# 执行action
18+
body = getattr(controller, request.router.action)()
19+
response.template = body["template"]
20+
response.heads["Content-Type"] = content_types[body["type"]]
21+
else:
22+
response.template = ""
23+
return True
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def response_middleware(app, request, response, config):
2+
# 获取响应状态信息
3+
status = statusCodes[response.status]
4+
# 获取响应头信息
5+
heads = []
6+
for (key, value) in response.heads.items():
7+
heads.append((key, value))
8+
# 写入响应头
9+
from pprint import pprint
10+
pprint(heads)
11+
response.write(status, heads)
12+
# 写入响应体
13+
response.send(response.template)
14+
15+
16+
statusCodes = {
17+
200: "200 OK"
18+
}
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
def router_middleware(app, request, response, config):
2+
router_map = {
3+
1: mvcRouter
4+
}
5+
request.router = router_map[config["router"]["model"]](request.url, config)
6+
return True
7+
8+
9+
class router:
10+
def __init__(self, url, config):
11+
self.url = url
12+
self._controller = config["router"]["controller"]
13+
self._action = config["router"]["action"]
14+
self._parameters = None
15+
self._parse()
16+
17+
@property
18+
def controller(self):
19+
return self._controller
20+
21+
@property
22+
def action(self):
23+
return self._action
24+
25+
@property
26+
def parameters(self):
27+
return self._parameters
28+
29+
def _parse(self):
30+
pass
31+
32+
33+
class mvcRouter(router):
34+
def __init__(self, url, config):
35+
super().__init__(url, config)
36+
37+
def _parse(self):
38+
if self.url:
39+
str_arr = self.url.split("/")
40+
if str_arr and len(str_arr) > 2:
41+
self._controller = str_arr[1]
42+
self._action = str_arr[2]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def session_middleware(app, request, response, config):
2+
sessionId = getattr(request.cookie, config["session"]["id"])
3+
if not sessionId:
4+
sessionId = app.guid()
5+
setattr(response.cookie, config["session"]["id"], sessionId)
6+
request.session = response.session = sessions(app, sessionId)
7+
return True
8+
9+
10+
class sessions:
11+
def __init__(self, app, sessionId):
12+
self.__dict__["app"] = app
13+
self.__dict__["sessionId"] = sessionId
14+
15+
def __setattr__(self, key, value):
16+
if not hasattr(self.__dict__["app"], "store"):
17+
self.__dict__["app"].store = {}
18+
self.__dict__["app"].store[key] = value
19+
20+
def __getattr__(self, key):
21+
return self.__dict__["app"].store[self.__dict__["sessionId"]][key]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def static_middleware(app, request, response, config):
2+
suffix = request.url.split(".").pop()
3+
if suffix in config["static"]["suffix"]:
4+
file = "{path}/{filename}".format(path=config["static"]["path"], filename=request.url) # NOQA
5+
with open(file, 'rb') as f:
6+
response.send(f.read())
7+
response.write("200 OK", [("Content-Type", "application/octet-stream")]) # NOQA
8+
return False
9+
return True
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import re
2+
3+
4+
def template_middleware(app, request, response, config):
5+
html = response.template.replace('\n', ' ').replace('\r', '')
6+
html = re.sub("<%(.*?)%>", replace_function, html)
7+
html = re.sub("<<(.*?)>>", replate_object, html)
8+
print(html)
9+
html = "'{html}'".format(**locals())
10+
response.template = eval(html)
11+
return True
12+
13+
14+
def replace_function(match):
15+
pass
16+
17+
18+
def replate_object(match):
19+
return "'+response.views[\"{obj}\"]+'".format(obj=match.group(1))

setup.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from setuptools import find_packages, setup
2+
3+
setup(name='autumn-mvc',
4+
version='1.0',
5+
description='一个依赖大于配置的MVC框架',
6+
author='Guifa Li',
7+
author_email='[email protected]',
8+
url='https://www.github.com/liguifa/autumnMVC')

0 commit comments

Comments
 (0)