Django(二)

django三板斧

django自动重启的现象叫‘热更新’

如果setting.py文件中DEBUG = False,则必须在ALLOWED_HOSTS = []中填写对应ip地址或者*号

1. HttpResponse

2. render

3. redirect

def index(request):
print('123')
# 暂且记忆返回值是字符串类型
# return HttpResponse('hello django!') # 返回给浏览器了
ctime = time.strftime('%Y-%m-%d %X')
a = 1
b = 2
print(locals())
# return render(request, 'index.html', {'ctime11111':ctime, 'a':1, 'b':2})
# return render(request, 'index.html', locals())
# return redirect('http://www.baidu.com')
return redirect('/admin/') # ip+port/admin 括号内可跟链接地址,直接跳转

静态文件配置

什么是静态文件
css, js, jq, bootstrap, img...
eg:
以登录功能为例
# 静态文件的存储路径一般是static,默认是没有这个文件夹的,所以,需要我们自己手动创建出来这个文件夹

在static文件夹中还可以继续根据不同的功能进行划分

js
css
lib
img

http://127.0.0.1:8000/static/css/bootstrap.min.css不能访问是因为后盾没有开放可访问的路径

{# 动态引入 #}
{% load static %}

STATIC_URL = '/aaaaa/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'), # 这样一配置完成,静态路径的根就是static
os.path.join(BASE_DIR, 'static1'), # 这样一配置完成,静态路径的根就是static
os.path.join(BASE_DIR, 'static2'), # 这样一配置完成,静态路径的根就是static
]

form表单


'''
1. 什么都不写,提交到当前页面
2. 全写:https://passport.baidu.com/v2/api/?login
3. 只写后缀
/login/ => 自动补全ip和端口
http://127.0.0.1:8000/login/
'''

面试题:get和post的区别?
http://127.0.0.1:8000/login/?a=1&b=2&c=3
'''
get请求:
1. get没有请求体
2. 对数据大小的限制是4KB
3. 不安全,因为参数直接暴露在URL上,所以不能用来传递敏感信息
post请求:
1. post有请求体
2. 理论上对数据大小没有限制
3. 相对安全
'''

'''
MySQL中可能会出现的安全问题:SQL注入
前端当中可能会出现的安全问题:xss攻击
django中会出现的安全问题:csrf跨站请求
'''

def login(request):
# 1. 如何判断请求方式?
print(request) # <WSGIRequest: GET '/login/'>
print(request.method, type(request.method)) # GET <WSGIRequest: GET '/login/'>
if request.method == 'POST':
# 2. 如何获取post请求方式的数据?
# print(request.POST) # QueryDict: {'user': ['ly'], 'password': ['123']}>
# print(request.POST.get('username')) # ly
# # get只能拿最后一个值
# print(request.POST.get('hobby')) # ly
# print(request.POST.getlist('hobby')) # 拿到所有的值
username = request.POST.get('username')
password = request.POST.get('password')

if username == 'ly' and password =='123':
return HttpResponse('登录成功')
else:
return HttpResponse('密码错误')
return render(request, 'login.html', )

django连接mysql

连接mysql的配置

'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db8_3',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD':'123',
'CHARSET':'utf8'
}

django默认的操作mysql的模块是MySQLdb

'''
在python3.6版本以下,需要加入下面两句话
需要先安装pymysql
pip3 install pymysql

import pymysql
pymysql.install_as_MySQLdb()
'''

posted @ 2022-03-02 19:14  丶祈安  阅读(177)  评论(0)    收藏  举报