Python 一路走来 Django
Web 框架 (本质:socket)
Python web框架
自己实现socket
- Tornado
基于wsgi
-djago
所有web框架由以下扩展:
#!/usr/bin/env python #coding:utf-8 import socket def handle_request(client): buf = client.recv(1024) client.send("HTTP/1.1 200 OK\r\n\r\n") client.send("Hello, Seven") def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost',8000)) sock.listen(5) while True: connection, address = sock.accept() handle_request(connection) connection.close() if __name__ == '__main__': main()
client.send 可以换成读取文件
WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦。
自己开发一个web框架(基于wsgi):
#!/usr/bin/env python #coding:utf-8 from wsgiref.simple_server import make_server def RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return '<h1>Hello, web!</h1>' if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print "Serving HTTP on port 8000..." httpd.serve_forever()
# while true:
#socket.accept() #内部本质做了这两步
MVC/MTV
处理用户请求 放置HTML模版 操作数据库
Controllers Views Modals
Views Template Modals
Django > MTV
Django
安装:
pip3 install django
添加环境变量
1.创建project
django-admin startproject mysite
mysite
mysite:
-setting.py #配置文件
-url.py #路由系统
-wsgi #WSGI
manage.py #django程序启动文件
2. 创建app
teminal cd mysite
python3 manage.py startapp cmdb
3。 编写代码
urls.py
view.py
4. 启动django
python3 manage.py runserver 127.0.0.1:8000
5. 使用模版
setting配置
render(request,'路径')
6.静态文件配置
STATIC_URL = '/fff/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'statics'),
)
7. 连接数据库
注册app
settings.py
INTSALLED_APPS -[
'cmdb',
]
models:
class UserInfo(models.Model):
user = models.CharField(max_length=32)
email = models.CharField(max_length=32)
执行命令:
python3 manage.py makemigrations
python3 manage.py migrate