1.状态代码的第一个数字代表当前响应的类型:
http://www.luffycity.com:80/news/index.html?id=250&page=1
www.luffycity.com
,是服务器示例一:socket服务端
import socket
# 创建一个socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen(5)
# 等待连接
while True:
conn, addr = sk.accept()
# 接收数据
data= conn.recv(1024)
print(data)
# 返回数据
conn.send(b'HTTP/1.1 200 OK\r\n\r\n<h1>ok!</h1>')
# 断开连接
conn.close()
示例二:根据不同路径返回不同的内容(普通版)
import socket
# 创建一个socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen(5)
# 等待连接
while True:
conn, addr = sk.accept()
# 接收数据
data = conn.recv(1024)
data = data.decode('utf-8')
url = data.split()[1]
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
if url == '/index/':
# 返回数据
conn.send(b'<h1>index!</h1>')
elif url == '/home/':
conn.send(b'<h1>home!</h1>')
else:
conn.send(b'<h1>404 not found!</h1>')
# 断开连接
conn.close()
示例三:根据不同路径返回不同的内容(函数版)
import socket
# 创建一个socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen(5)
# 函数
def index(url):
ret = '<h1>index!</h1>({})'.format(url)
return ret.encode('utf-8')
def home(url):
ret = '<h1>home!</h1>({})'.format(url)
return ret.encode('utf-8')
# 等待连接
while True:
conn, addr = sk.accept()
# 接收数据
data = conn.recv(1024)
data = data.decode('utf-8')
url = data.split()[1]
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
if url == '/index/':
# 返回数据
ret = index(url)
elif url == '/home/':
ret = home(url)
else:
ret = b'<h1>404 not found!</h1>'
conn.send(ret)
# 断开连接
conn.close()
示例四:根据不同路径返回不同的内容(函数进阶版)
import socket
# 创建一个socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen(5)
# 函数
def index(url):
ret = '<h1>index!</h1>({})'.format(url)
return ret.encode('utf-8')
def home(url):
ret = '<h1>home!</h1>({})'.format(url)
return ret.encode('utf-8')
# 定义一个list1和实际要执行的函数的对应关系
list1 = [
('/index/', index),
('/home/', home),
]
# 等待连接
while True:
conn, addr = sk.accept()
# 接收数据
data = conn.recv(1024)
data = data.decode('utf-8')
url = data.split()[1]
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
func = None
for i in list1:
if url == i[0]:
func = i[1]
break
if func:
ret = func(url)
else:
ret = b'<h1>404 not found!</h1>'
conn.send(ret)
# 断开连接
conn.close()
示例五:返回HTML页面
import socket
# 创建一个socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen(5)
# 函数
def index(url):
with open('index.html','rb') as f:
ret = f.read()
return ret
def home(url):
ret = '<h1>home!</h1>({})'.format(url)
return ret.encode('utf-8')
# 定义一个list1和实际要执行的函数的对应关系
list1 = [
('/index/', index),
('/home/', home),
]
# 等待连接
while True:
conn, addr = sk.accept()
# 接收数据
data = conn.recv(1024)
data = data.decode('utf-8')
url = data.split()[1]
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
func = None
for i in list1:
if url == i[0]:
func = i[1]
break
if func:
ret = func(url)
else:
ret = b'<h1>404 not found!</h1>'
conn.send(ret)
# 断开连接
conn.close()
示例六:返回动态页面
import socket
import time
# 创建一个socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen(5)
# 函数
def index(url):
with open('index.html', 'rb') as f:
ret = f.read()
return ret
def home(url):
ret = '<h1>home!</h1>({})'.format(url)
return ret.encode('utf-8')
def timer(url):
now = time.strftime('%H:%M:%S')
with open('time.html','r',encoding='utf-8') as f:
data = f.read()
data = data.replace('xxtimexx',now)
return data.encode('utf-8')
# 定义一个list1和实际要执行的函数的对应关系
list1 = [
('/index/', index),
('/home/', home),
('/time/', timer),
]
# 等待连接
while True:
conn, addr = sk.accept()
# 接收数据
data = conn.recv(1024)
data = data.decode('utf-8')
url = data.split()[1]
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
func = None
for i in list1:
if url == i[0]:
func = i[1]
break
if func:
ret = func(url)
else:
ret = b'<h1>404 not found!</h1>'
conn.send(ret)
# 断开连接
conn.close()
补充:time.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>当前时间是:@@time@@</h1>
</body>
</html>
常用的WSGI服务器有uWSGI、Gunicorn
示例:
"""
根据URL中不同的路径返回不同的内容--函数进阶版
返回HTML页面
让网页动态起来
wsgiref模块版
"""
from wsgiref.simple_server import make_server
# 将返回不同的内容部分封装成函数
def index(url):
# 读取index.html页面的内容
with open("index.html", "r", encoding="utf8") as f:
s = f.read()
# 返回字节数据
return bytes(s, encoding="utf8")
def home(url):
with open("home.html", "r", encoding="utf8") as f:
s = f.read()
return bytes(s, encoding="utf8")
def timer(url):
import time
with open("time.html", "r", encoding="utf8") as f:
s = f.read()
s = s.replace('@@time@@', time.strftime("%Y-%m-%d %H:%M:%S"))
return bytes(s, encoding="utf8")
# 定义一个url和实际要执行的函数的对应关系
list1 = [
("/index/", index),
("/home/", home),
("/time/", timer),
]
def run_server(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ]) # 设置HTTP响应的状态码和头信息
url = environ['PATH_INFO'] # 取到用户输入的url
func = None
for i in list1:
if i[0] == url:
func = i[1]
break
if func:
response = func(url)
else:
response = b"404 not found!"
return [response, ]
if __name__ == '__main__':
httpd = make_server('127.0.0.1', 8090, run_server)
print("我在8090等你哦...")
httpd.serve_forever()
模板渲染现成的工具:jinja2
示例:
from wsgiref.simple_server import make_server
from jinja2 import Template
def index(url):
# 读取HTML文件内容
with open("index2.html", "r", encoding="utf8") as f:
data = f.read()
template = Template(data) # 生成模板文件
ret = template.render({'name': 'alex', 'hobby_list': ['抽烟', '喝酒', '烫头']}) # 把数据填充到模板中
return bytes(ret, encoding="utf8")
def home(url):
with open("home.html", "r", encoding="utf8") as f:
s = f.read()
return bytes(s, encoding="utf8")
# 定义一个url和实际要执行的函数的对应关系
list1 = [
("/index/", index),
("/home/", home),
]
def run_server(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ]) # 设置HTTP响应的状态码和头信息
url = environ['PATH_INFO'] # 取到用户输入的url
func = None
for i in list1:
if i[0] == url:
func = i[1]
break
if func:
response = func(url)
else:
response = b"404 not found!"
return [response, ]
if __name__ == '__main__':
httpd = make_server('127.0.0.1', 8090, run_server)
print("我在8090等你哦...")
httpd.serve_forever()
补充:index2.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<h1>姓名:{{name}}</h1>
<h1>爱好:</h1>
<ul>
{% for hobby in hobby_list %}
<li>{{hobby}}</li>
{% endfor %}
</ul>
</body>
</html>
下载安装
创建项目
启动
python36 manage.py runserver
—— 127.0.0.1:80`python36 manage.py runserver 80
——127.0.0.1:80python36 manage.py runserver 0.0.0.0:80
——0.0.0.0:80简单使用
# 在urls.py中
# 导入
from django.shortcuts import HttpResponse,render
# 函数
def index(request):
# return HttpResponse('index')
return render(request,'index.html')
# url和函数对应关系
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index),
]
配置
STATIC_URL = '/static/' # 别名
STATICFILES_DIRS = [ # 设置文件路径,可以设置多个
os.path.join(BASE_DIR, 'static1'),
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'static2'),
]
使用
<link rel="stylesheet" href="/static/css/login.css"> {# 别名开头 #}
form表单提交数据注意的问题:
提交post请求,由于Django中有一个csrf校验,所有请求会出问题
重定向
导入方式
from django.shortcuts import redirect
使用方式
在函数中使用:
return redirect('/index/') #参数 url
#注意:前面必须加/,代表从url根拼接,否则就会在当前url后面一直拼接
示例:
from django.shortcuts import HttpResponse, render, redirect
def index(request):
# return HttpResponse('index')
return render(request, 'index.html')
def login(request):
if request.method == 'POST':
# 获取form表单提交的书籍
username = request.POST['username']
password = request.POST['password']
# 验证用户名和密码
if models.User.objects.filter(username=username,password=password):
# 验证成功跳转到index页面
# return redirect('https://www.baidu.com/')
return redirect('/index/')
# 不成功 重新登录
return render(request, 'login.html')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^login/', views.login),
]
创建app
注册app
INSTALLED_APPS = [
...
'app01',
'app01.apps.App01Config', # 推荐写法
]
app中的文件
创建一个MySQL数据库:create database day53;
在settings.py中设置,Django连接MySQL数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 引擎
'NAME': 'day53', # 数据库名称
'HOST': '127.0.0.1', # ip地址
'PORT':3306, # 端口
'USER':'root', # 用户
'PASSWORD':'123' # 密码
}
}
在与settings,py同级目录下的init文件中写入:
import pymysql
pymysql.install_as_MySQLdb()
创建表(在app下的models.py中写类):
from django.db import models
class User(models.Model):
username = models.CharField(max_length=32) # username varchar(32)
password = models.CharField(max_length=32) # username varchar(32)
执行数据库迁移的命令:
原文:https://www.cnblogs.com/hanfe1/p/12194618.html