小白学习django第六站-http相关
请求与相应
HttpRequest对象API
def home(request):
print('path:', request.path)
print('mothod:', request.method)
print('encoding:', request.encoding)
print('GET:', request.GET)
print('POST:', request.POST)
print('FILES', request.FILES)
print('COOKIES:', request.COOKIES)
print('session:', request.session)
print('is_ajax:', request.is_ajax()) path: /blog1/home/
mothod: GET
encoding: None
GET: <QueryDict: {}>
POST: <QueryDict: {}>
FILES <MultiValueDict: {}>
COOKIES: {'csrftoken': 'xnjakTTg7c8cy6pnyZzgKg8fkyXkMBcl3LXCnMeQC8n4oLIByU0U6Pr3DGCRj6EO', 'sessionid': '7it5s9n3zn8or27i9kxqiewjiq6rvjfb'}
session: <django.contrib.sessions.backends.db.SessionStore object at 0x7fbcd958f9e8>
is_ajax: False
views.py
def index(request):
print(request.path) # 请求路径
print(request.method) # 请求方法
print(request.encoding) # 编码格式
# return HttpResponse('1111')
return render(request, 'blog/get_post_test.html') def get_text(request):
# if request.method == 'GET':
# return render(request, 'blog/get_post_test.html')
# elif request.method == 'POST':
a = request.GET.get('a')
b = request.GET.get('b')
print(a, b)
return HttpResponse('xxxxxxxx') def post_text(request):
if request.method == 'GET':
return render(request, 'blog/get_post_test.html')
elif request.method == 'POST':
a = request.POST.getlist('a') # getlist 一键多值
# a = request.POST.get('a')
# b = request.POST.get('b')
# print(a, b)
print(a)
return HttpResponse('xxxxxxxx')
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{#<form action="" method="get">#}
{% csrf_token %} {# 防止跨域请求 #}
<input type="text" name="a" id="a">
<input type="text" name="a" id="b">
<input type="submit" value="提交" id="c"> </form>
</body>
</html>
类视图
views.py
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from .models import BlogModle2
from django.views import View
# Create your views here. class BlogIndex(View):
def get(self, request):
return render(request, 'blog/demo_index.html') class BlogAdd(View):
def get(self, request):
return render(request, 'blog/demo_add.html') def post(self, request):
title = request.POST.get('title')
content = request.POST.get('content')
blog = BlogModle2(title=title, content=content)
blog.save()
return render(request, 'blog/demo_add.html') class BlogList(View):
def get(self, request):
blog_list = BlogModle2.objects.all()
return render(request, 'blog/demo_list.html', context={'blog_list': blog_list}) class BlogDetail(View):
def get(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
return render(request, 'blog/demo_detail.html', context={'blog': blog}) class BlogDelete(View):
def get(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
if blog:
blog.delete()
return redirect(reverse('blog_list'))
else:
return HttpResponse('不存在这条博客') class BlogEdit(View): def get(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
return render(request, 'blog/demo_add.html', context={'blog': blog}) def post(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
blog.title = request.POST.get('title')
blog.content = request.POST.get('content')
blog.save()
return redirect(reverse('blog_list'))
urls.py
path('index/', views.BlogIndex.as_view(), name='blog_index'),
path('add/', views.BlogAdd.as_view(), name='blog_add'),
path('list/', views.BlogList.as_view(), name='blog_list'),
path('detail/<blog_id>', views.BlogDetail.as_view(), name='blog_detail'),
path('delete/<blog_id>', views.BlogDelete.as_view(), name='blog_delete'),
path('edit/<blog_id>', views.BlogEdit.as_view(), name='blog_edit'),
文件上传
先在settings.py设置路径
创建文件夹
编写views.py
import os
from mysite.settings import MEDIA_ROOT class Upload_file(View):
def get(self, request):
return render(request, 'blog/file.html') def post(self, request):
# f1 = request.FILES['file']
f1 = request.FILES.get('file')
f1_name = os.path.join(MEDIA_ROOT, f1.name)
with open(f1_name, 'wb') as f:
for i in f1.chunks():
f.write(i)
return HttpResponse('上传成功')
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file">
<input type="submit">
</form>
</body>
</html>
HttpResponse对象
属性
def index(request):
response = HttpResponse('')
print(response.content)
print(response.status_code)
print(response.charset) return response
方法
设置cookie
# 设置cookie
import datetime
def set_cookie(request):
response = HttpResponse('设置cookie')
response.write('我是写入进去的')
# response.set_cookie('name', 'ing', max_age=100) # 设置多少秒之后过期
response.set_cookie('name', 'ing', expires=datetime.datetime(2019, 9, 6)) # 设置过期日期 return response def get_cookie(request):
cookie = request.COOKIES
print(cookie.get('name'))
return HttpResponse('获取cookie') def delete_cookie(request):
rs = HttpResponse("删除cookie")
rs.delete_cookie('name')
return rs
返回json数据
登录案例,设置session,需要先执行makemigrations, migrate
def home(request): # 主页
a = 1
# b = a + '1'
print('只是我视图函数在调用')
username = request.session.get('username', '未登录')
return render(request, 'form_test/home.html', context={'username': username}) class LoginTest(View): # 登录
def get(self, request):
return render(request, 'form_test/login.html') def post(self, request):
username = request.POST.get('username')
request.session['username'] = username # 字典传值, 会存到数据库
request.session.set_expiry(None) # 设置过期时间, 默认两周
print(request.session)
return redirect(reverse('home')) def login_out(request): # 登出
request.session.flush() # 清除会话数据
return redirect(reverse('home'))
settings中设置
# 是否关闭浏览器使得session过期,默认False
# SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# 是否每次请求都保存session,默认修改之后保存
# SESSION_SAVE_EVERY_REQUEST = False
# session的cookie失效日期,默认两周
# SESSION_COOKIE_AGE = 1209600
创建models.py模型
from django.db import models # Create your models here.
class UserModel(models.Model):
username = models.CharField(max_length=30, unique=True)
password = models.CharField(max_length=100)
email = models.EmailField()
django form表单的使用,登录注册案例
views.py
from .models import UserModel
from .forms import RegisterForm, LoginForm class Register(View):
def get(self, request):
form = RegisterForm() # 实例化一个表单实例
return render(request, 'form_test/register.html', context={'form': form}) def post(self, request):
form = RegisterForm(request.POST) # 获取form表单的数据
if form.is_valid(): # 验证数据是否合法
username = form.cleaned_data.get('username') # 拿数据
password = form.cleaned_data.get('password')
password_repeat = form.cleaned_data.get('password_repeat')
email = form.cleaned_data.get('email')
if password == password_repeat:
UserModel.objects.create(username=username, password=password, email=email)
return HttpResponse('注册成功')
else:
return HttpResponse('注册失败') else:
return HttpResponse('两次密码不一致') class Login(View):
def get(self, request):
form =LoginForm() # 先获得表单实例
return render(request, 'form_test/login.html', context={'form': form}) def post(self, request):
form = LoginForm(request.POST) # 获取发送的请求值
if form.is_valid(): # 检测数据是否合法
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = UserModel.objects.filter(username=username, password=password)
if user:
request.session['username'] = username
return redirect(reverse('home'))
else:
return redirect(reverse('register'))
else:
return HttpResponse('登录失败')
forms.py
from django import forms # 可以验证也可以生成前端代码
class RegisterForm(forms.Form): # 注册表单
username = forms.CharField(max_length=30, min_length=6)
password = forms.CharField(max_length=30, min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
password_repeat = forms.CharField(max_length=30, min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
email = forms.EmailField() class LoginForm(forms.Form): # 登录表单
username = forms.CharField(max_length=30, min_length=6,
widget=forms.TextInput(attrs={'placeholder': '请输入用户名'}))
password = forms.CharField(max_length=30, min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
{# <input type="text" name="username">#}
<input type="submit" value="登录"> </form>
</body>
</html> <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="注册">
</form>
{{ username }}
</body>
</html>
小白学习django第六站-http相关的更多相关文章
- 小白学习django第四站-关联数据库
使用mysql连接django首先要配置好相关环境 首先在setting.py配置数据库信息(需要现在mysql中创建一个数据库) 在setting.py那个目录的__init__.py文件中写入 之 ...
- 小白学习django第五站-简易案例
首先在setting.py文件中编写数据库配置内容 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': ' ...
- 小白学习django第三站-自定义过滤器及标签
要使用自定义过滤器和标签,首先要设置好目录结构 现在项目目录下建立common的python包 再将common加入到setting.py中的INSTALLED_APP列表中 在common创建目录t ...
- 小白学习django第一站-环境配置
Django简单来说就是用Python开发的一个免费开源的Web框架 使用Django,使你能够以最小的代价构建和维护高质量的Web应用. 开搞!!! 工具准备: linux(ubuntu) + py ...
- 小白学习django第二站-模版配置
上一站说道app创建,接下来我们来配置app的url路由 首先需要到setting.py中添加book这个app, 再到django_test文件里的urls添加路由 include() : 这个函数 ...
- 小白学习Spark系列六:Spark调参优化
前几节介绍了下常用的函数和常踩的坑以及如何打包程序,现在来说下如何调参优化.当我们开发完一个项目,测试完成后,就要提交到服务器上运行,但运行不稳定,老是抛出如下异常,这就很纳闷了呀,明明测试上没问题, ...
- 小白学习tornado框架第一站-环境设置
首先建立一个虚拟环境 mkvirtualenv -p /usr/bin/python3 tornado_1 安装tornado框架 pip install tornado pycham中建立同步 创 ...
- 学习django就看这本书了!django book 2.0中文版
所属网站分类: 资源下载 > python电子书 作者:熊猫烧香 链接:http://www.pythonheidong.com/blog/article/29/ 来源:python黑洞网 dj ...
- 小白神器 - Django - 起步
小白神器 - Django - 起步 一. Django下载 1. 命令行 pip install django==1.11.16 pip install django==1.11.16 -i ht ...
随机推荐
- Linux 如何查看端口与进程占用情况
1 lsof -i:port 查看端口使用情况 lsof -i 如果出现 command not found,直接yum install lsof即可. (1) lsof -i lsof -i 用以 ...
- 12 Linux ACL权限
1.查看facl权限 getfacl /home/test.txt [root@localhost ~]# getfacl /home/test.txt getfacl: Removing leadi ...
- SpringBoot2.X 静态文件配置
Spring Boot 默认会挨个从 META/resources > resources > static > public 里面找是否存在相应的资源,如果有则直接返回. 默认配置 ...
- 学习笔记01:《开放平台产品成长之路-POP》
当看到一些比较好的书籍和视频内容时,希望自己可以总价归纳下来,一方面是好的东西希望可以分享给大家,另一方面希望自己能很好的吸收并转化成掌握的知识,所以有了这个系列的学习笔记,共勉,今天的你比昨天更博学 ...
- selenium爬虫使用
1. 网页的打开 from selenium import webdriver import time driver = webdriver.Chrome(executable_path=r" ...
- Android jni/ndk编程五:jni异常处理
在Java的编程中,我们经常会遇到各种的异常,也会处理各种的异常.处理异常在java中非常简单,我们通常会使用try-catch-finally来处理,也可以使用throw简单抛出一个异常.那么在jn ...
- LC 833. Find And Replace in String
To some string S, we will perform some replacement operations that replace groups of letters with ne ...
- Unix介绍
1965年,AT&T贝尔电话实验室.通用电气公司.麻省理工学院MAC课题组一起联合开发一个称为Multics的新操作系统.该项目目的是让大型主机可以同时提供300台以上的终端机连接使用.其被设 ...
- 【转】C++ 资源大全中文版
转自:http://www.cnblogs.com/liuliu-NoGirl/p/5802765.html 感谢作者发布这么东西 我想很多程序员应该记得 GitHub 上有一个 Awesome – ...
- MyBatis Mapper Demo
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-/ ...