请求与相应

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相关的更多相关文章

  1. 小白学习django第四站-关联数据库

    使用mysql连接django首先要配置好相关环境 首先在setting.py配置数据库信息(需要现在mysql中创建一个数据库) 在setting.py那个目录的__init__.py文件中写入 之 ...

  2. 小白学习django第五站-简易案例

    首先在setting.py文件中编写数据库配置内容 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': ' ...

  3. 小白学习django第三站-自定义过滤器及标签

    要使用自定义过滤器和标签,首先要设置好目录结构 现在项目目录下建立common的python包 再将common加入到setting.py中的INSTALLED_APP列表中 在common创建目录t ...

  4. 小白学习django第一站-环境配置

    Django简单来说就是用Python开发的一个免费开源的Web框架 使用Django,使你能够以最小的代价构建和维护高质量的Web应用. 开搞!!! 工具准备: linux(ubuntu) + py ...

  5. 小白学习django第二站-模版配置

    上一站说道app创建,接下来我们来配置app的url路由 首先需要到setting.py中添加book这个app, 再到django_test文件里的urls添加路由 include() : 这个函数 ...

  6. 小白学习Spark系列六:Spark调参优化

    前几节介绍了下常用的函数和常踩的坑以及如何打包程序,现在来说下如何调参优化.当我们开发完一个项目,测试完成后,就要提交到服务器上运行,但运行不稳定,老是抛出如下异常,这就很纳闷了呀,明明测试上没问题, ...

  7. 小白学习tornado框架第一站-环境设置

    首先建立一个虚拟环境 mkvirtualenv -p /usr/bin/python3 tornado_1 安装tornado框架 pip install tornado  pycham中建立同步 创 ...

  8. 学习django就看这本书了!django book 2.0中文版

    所属网站分类: 资源下载 > python电子书 作者:熊猫烧香 链接:http://www.pythonheidong.com/blog/article/29/ 来源:python黑洞网 dj ...

  9. 小白神器 - Django - 起步

    小白神器 - Django - 起步 一.  Django下载 1. 命令行 pip install django==1.11.16 pip install django==1.11.16 -i ht ...

随机推荐

  1. SCOI2009迷路

    当初学矩阵幂的时候弃掉了,那时候只会用矩阵优化递推,碰到这种图论的瞬间躺地. 昨天听学长的课,有一道例题,在边权为一的图上求从某点到某点的路径方案数,只要对邻接矩阵跑qpow就完事了. 于是自己画了个 ...

  2. Linux停止被占用的端口

    查找被占用的端口:netstat -lnp|grep 80 查看80端口被那些服务占用. kill掉该进程 kill -9 5574 然后在去查看一下80被占用的情况netstat -lnp|grep ...

  3. linux安装软件时/usr/lib/python2.7/site-packages/urlgrabber/grabber.py文件异常

    linux安装软件时,经常出现以下异常信息 Traceback (most recent call last): File , in <module> main() File , in m ...

  4. PHP 分页 (分页类)

    分页类  以后可直接使用 /** file: page.class.php 完美分页类 Page */ class Page { private $total; //数据表中总记录数 private ...

  5. pandas.DataFrame 中的insert(), pop()

    pandas.DataFrame 中的insert(), pop() 在pandas中,del.drop和pop方法都可以用来删除数据,insert可以在指定位置插入数据. 可以看看以下示例. imp ...

  6. SprintBoot日志

    yml配置 #logging logging.file: "logs/app.log" logging: level: root: debug file: max-size: 10 ...

  7. IIS 报错试图加载格式不正确的程序集解决办法

    原因: 64位系统和32系统不匹配导致. 解决办法: 方法一.注册32位IIS(必须卸载64位IIS) 使用命令 X:WindowsMicrosoft.NETFramework64v4.0.30319 ...

  8. Prism框架 如何在主程序中合理的弹出子窗体

    说起子窗体,大家都会想到ChildWindow,多熟悉的一个控件.不错,Sliverlight中已经提供了子窗体的具体实现,而在WPF中却没有这么好的事情(有的第三方控件商已经提供此控件).最常见的实 ...

  9. 我非要捅穿这 Neutron(四)Open vSwitch in Neutron

    目录 文章目录 目录 前文列表 OvS In Neutron 网络拓扑 OvS In Neutron 网络实现模型 双节点混合平面网络 双节点网络拓扑 OvS Bridges 与初始流表项 OvS b ...

  10. 自在因梦 | 威爾伯的Fourth Turning所引發的聯想

    2015-05-06                                                 胡因梦                                       ...