django 文件上传和菜单分级,mysql支持事务,F模块自增字段, python发送get,post请求

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
一、文件上传
方法一
 
上传文件视图函数
def  upload_img(request):
     obj  =  request.FILES.get( 'file' )     #前端js设置的key
 
     img_path  =  os.path.join( 'static' , 'img' ,obj.name)
 
     with  open (img_path,mode = 'wb' ) as f:
         for  chunk  in  obj.chunks():
             f.write(chunk)
     data  =  {
         'status' True ,
         'path' : img_path
     }
     import  json
     return  HttpResponse(json.dumps(data))
     
     
前端页面
form表单
             <form>
                   <div  class = "form-group" >
                     <label  for = "exampleInputFile" >上传图片< / label>
                     < input  type = "file"  id = "exampleInputFile" >
                       <button  type = "button"  class = "btn btn-default"  id = "uploadfile" >上传< / button>
{ #                    <p class="help-block">Example block-level help text here.</p>#}
                   < / div>
 
                   <div  class = "form-group" >
                       <label  for = "select_news" >选择新闻类型< / label>
                       <select  class = "form-control"  id = "select_news" >
                           <option> 42 区< / option>
                           <option>段子< / option>
                           <option>图片< / option>
                           <option>挨踢 1024 < / option>
                           <option>你问我答< / option>
                       < / select>
                   < / div>
                   <div  class = "form-group" >
                     <label  for = "news_url" >新闻链接< / label>
                     < input  type = "text"  class = "form-control"  id = "news_url"  placeholder = "Url" >
                   < / div>
 
                   <div  class = "form-group" >
                     <label  for = "news_title" >新闻标题< / label>
                     <textarea  class = "form-control"  rows = "3"  id = "news_title" >< / textarea>
                   < / div>
 
                   <div  class = "form-group" >
                     <label  for = "news_summary" >新闻简介< / label>
                     <textarea  class = "form-control"  rows = "3"  id = "news_summary" >< / textarea>
                   < / div>
 
                   <div  class = "modal-footer" >
                     <button  type = "button"  class = "btn btn-default"  data - dismiss = "modal" >关闭< / button>
                     <button  type = "button"  class = "btn btn-primary"  id = "news_publish" >提交< / button>
                   < / div>
               < / form>
               
 
js 通过FormData方法处理
$(document).ready(function () {
     $( '#uploadfile' ).click(function () {
         var formData  =  new FormData();
         formData.append( 'file' ,$( '#exampleInputFile' )[ 0 ].files[ 0 ]);
         $.ajax({
             url:  '/upload' ,
             type 'POST' ,
             data: formData,
             processData: false,  / / 添加这两个参数,表示将原生文件发到后台
             contentType: false,
             success: function (res) {
                 console.log(res);
             }
         })
     })
});
 
 
 
方法二
 
前端页面用form和iframe组合伪造ajax提交
<form method = "POST"  target = "xxxxxx"  action = "/upload_img2/"  enctype = "multipart/form-data" >
         { %  csrf_token  % }
         < input  type = "text"  name = "user"  / >
         <a style = "width: 60px;height: 30px;background-color: darkslateblue;color: white;display: inline-block;position: relative;" >
             上传
             < input  type = "file"  name = "avatar"  style = "opacity: 0;position: absolute;left: 0;top:0;right: 0;bottom: 0;"  / >
         < / a>
         < input  type = "submit"  value = "提交"  / >
< / form>
<iframe  id = "ifm"  name = "xxxxxx"  onload = "successCallback(this);"  style = "display: none;"  >< / iframe>
 
注: form属性target的值必须和iframe的name属性值一样
 
 
view视图函数处理上传请求
def  upload_img2(request):
     response  =  BaseResponse()
     try :
         user  =  request.POST.get( 'user' )     #处理post请求
         obj  =  request.FILES.get( 'avatar' )     #处理上传文件
         img_path  =  os.path.join( 'static' 'img' , obj.name)
         with  open (img_path,mode = 'wb' ) as f:
             for  chunk  in  obj.chunks():
                 f.write(chunk)
     except  Exception as e:
         response.msg  =  str (e)
     else :
         response.status  =  True
         response.data  =  img_path
     return  HttpResponse(json.dumps(response.get_dict()))
     
 
 
二、django对mysql事务的支持
view视图
 
import  json
from  django.db.models  import  F     # F模块实现数据库字段自增
from  django.db  import  transaction     #支持事务原子性,对数据库的连续操作,操作成功必须每个sql都成功,否则都失败
from  utils.response  import  LikeResponse
 
def  do_like(request):
     """
     点赞
     :param request:
     :return:
     """
     response  =  LikeResponse()
     try :
         new_id  =  request.POST.get( 'newId' )
         # 当前登录用户ID
         # uid = request.session.get('uid')
         uid  =  1
 
         exist_like  =  models.Like.objects. filter (nnew_id = new_id,uuser_id = uid).count()
         with transaction.atomic():     #事务
             if  exist_like:
                 models.Like.objects. filter (nnew_id = new_id, uuser_id = uid).delete()
                 models.News.objects. filter ( id = new_id).update(like_count = F( 'like_count' -  1 )
                 response.code  =  666
             else :
                 models.Like.objects.create(nnew_id = new_id,uuser_id = uid)
                 models.News.objects. filter ( id = new_id).update(like_count = F( 'like_count' +  1 )
                 response.code  =  999
     except  Exception as e:
         response.msg  =  str (e)
     else :
         response.status  =  True
     return  HttpResponse(json.dumps(response.get_dict()))
     
     
   三、多级菜单,多级评论
   
view视图
from  django.shortcuts  import  render, HttpResponse, redirect
 
# Create your views here.
import  json
from  django.db.models  import  F
from  app01  import  models
from  django.db  import  transaction
from  utils.response  import  LikeResponse
 
def  comment_list(request):
     li  =  [
         { 'id' 1 'user' '银秋良' 'content' '灌我鸟事' 'parent_id' None },
         { 'id' 2 'user' '银秋良' 'content' '管我鸟事' 'parent_id' None },
         { 'id' 3 'user' '型谱' 'content' '你个文盲' 'parent_id' 1 },
         { 'id' 4 'user' '详解' 'content' '好羡慕你们这些没脸的人呀' 'parent_id' 2 },
         { 'id' 5 'user' '银秋良' 'content' '你是流氓' 'parent_id' 3 },
         { 'id' 6 'user' '银秋良' 'content' '你冷库无情' 'parent_id' 5 },
         { 'id' 7 'user' '银秋良' 'content' '你才冷酷无情' 'parent_id' 4 },
         { 'id' 8 'user' '银秋良' 'content' '你无理取闹' 'parent_id' 4 },
     ]
 
     com_list  =  build_comment_data(li)
     html  =  build_comment_tree(com_list)
 
     return  render(request,  'comment_list.html' , { 'comment_html' : html})
  
  #将列表子元素放入父级元素中   
def  build_comment_data(li):
     dic  =  {}
     for  item  in  li:
         item[ 'children' =  []
         dic[item[ 'id' ]]  =  item
 
     result  =  []
     for  item  in  li:
         pid  =  item[ 'parent_id' ]
         if  pid:
             dic[pid][ 'children' ].append(item)
         else :
             result.append(item)
     return  result
 
#生成 html页面
def  build_comment_tree(com_list):
     tpl  =  """
     <div class='item'>
         <div class='title'>{0}:{1}</div>
         <div class='body'>{2}</div>
     </div>
     """
 
     html  =  ""
     for  item  in  com_list:
         if  not  item[ 'children' ]:
             html  + =  tpl. format (item[ 'user' ],item[ 'content' ],"")
         else :
             html  + =  tpl. format (item[ 'user' ], item[ 'content' ], build_comment_tree(item[ 'children' ]))
     return  html
     
comment_list.html页面
<!DOCTYPE html>
<html lang = "en" >
<head>
     <meta charset = "UTF-8" >
     <title>Title< / title>
     <style>
         .body{
             margin - left:  30px ;
         }
         .hide{
             display: none;
         }
 
     < / style>
< / head>
<body>
     <h1>评论< / h1>
     {{ comment_html|safe }}
 
     <h1>菜单< / h1>
     <hr / >
     <script src = "/static/jquery-3.1.1.js" >< / script>
     <script>
         $(function () {
             $( '.title' ).click(function () {
                 if  ($(this). next ().hasClass( 'hide' )){
                     $(this). next ().removeClass( 'hide' );
                 } else {
                     $(this). next ().addClass( 'hide' );
                 }
             })
         })
     < / script>
 
< / body>
< / html>
 
四、python实现get和post请求
客户端:
import  requests
response  =  requests.get('
 
传递字典类型参数
data_dict  =  {
'k1' : 'v1' ,
'k2' : 'v2'
}
content - type : application / x - www - form - urlencoded 
response  =  requests.post('
  print (response.text)
  
传递json类型参数
content - type : appcation / json
response  =  requests.post('
  print (response.text)
  
  
  服务端Django:
  from  django.views.decorators.csrf  import  csrf_exempt,csrf_protect
  @csrf_exempt
  def  asset(request):
  if  request.method  = =  "GET" :
      return  HttpResponse( '收到:GET' )
  else :
      print (request.POST)
      print (request.body)
  return  HttpResponse( '收到:POST' )
 






     本文转自小白的希望 51CTO博客,原文链接http://blog.51cto.com/haoyonghui/1968750:,如需转载请自行联系原作者





 

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
27天前
|
关系型数据库 MySQL Docker
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
|
5天前
|
存储 缓存 关系型数据库
MySQL底层概述—9.ACID与事务
本文介绍了数据库事务的ACID特性(原子性、一致性、隔离性、持久性),以及事务控制的演进过程,包括排队、排它锁、读写锁和MVCC(多版本并发控制)。文章详细解释了每个特性的含义及其在MySQL中的实现方式,并探讨了事务隔离级别的类型及其实现机制。重点内容包括:ACID特性(原子性、持久性、隔离性和一致性的定义及其实现方式)、事务控制演进(从简单的全局排队到复杂的MVCC,逐步提升并发性能)、MVCC机制(通过undo log多版本链和Read View实现高效并发控制)、事务隔离级别(析了四种隔离级别(读未提交、读已提交、可重复读、可串行化)的特点及适用场景)、隔离级别与锁的关系。
|
1月前
|
SQL 关系型数据库 MySQL
MySQL事务日志-Undo Log工作原理分析
事务的持久性是交由Redo Log来保证,原子性则是交由Undo Log来保证。如果事务中的SQL执行到一半出现错误,需要把前面已经执行过的SQL撤销以达到原子性的目的,这个过程也叫做"回滚",所以Undo Log也叫回滚日志。
MySQL事务日志-Undo Log工作原理分析
|
2月前
|
SQL 安全 关系型数据库
【MySQL基础篇】事务(事务操作、事务四大特性、并发事务问题、事务隔离级别)
事务是MySQL中一组不可分割的操作集合,确保所有操作要么全部成功,要么全部失败。本文利用SQL演示并总结了事务操作、事务四大特性、并发事务问题、事务隔离级别。
【MySQL基础篇】事务(事务操作、事务四大特性、并发事务问题、事务隔离级别)
|
2月前
|
SQL 关系型数据库 MySQL
数据库灾难应对:MySQL误删除数据的救赎之道,技巧get起来!之binlog
《数据库灾难应对:MySQL误删除数据的救赎之道,技巧get起来!之binlog》介绍了如何利用MySQL的二进制日志(Binlog)恢复误删除的数据。主要内容包括: 1. **启用二进制日志**:在`my.cnf`中配置`log-bin`并重启MySQL服务。 2. **查看二进制日志文件**:使用`SHOW VARIABLES LIKE &#39;log_%&#39;;`和`SHOW MASTER STATUS;`命令获取当前日志文件及位置。 3. **创建数据备份**:确保在恢复前已有备份,以防意外。 4. **导出二进制日志为SQL语句**:使用`mysqlbinlog`
117 2
|
2月前
|
关系型数据库 MySQL 数据库
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
385 15
|
2月前
|
SQL 关系型数据库 MySQL
MySQL进阶突击系列(04)事务隔离级别、AICD、CAP、BASE原则一直搞不懂? | 看这篇就够了
本文详细介绍了数据库事务的四大特性(AICD原则),包括原子性、隔离性、一致性和持久性,并深入探讨了事务并发问题与隔离级别。同时,文章还讲解了分布式系统中的CAP理论及其不可能三角关系,以及BASE原则在分布式系统设计中的应用。通过具体案例和图解,帮助读者理解事务处理的核心概念和最佳实践,为应对相关技术面试提供了全面的知识准备。
|
3月前
|
设计模式 前端开发 数据库
Python Web开发:Django框架下的全栈开发实战
【10月更文挑战第27天】本文介绍了Django框架在Python Web开发中的应用,涵盖了Django与Flask等框架的比较、项目结构、模型、视图、模板和URL配置等内容,并展示了实际代码示例,帮助读者快速掌握Django全栈开发的核心技术。
269 45
|
4月前
|
存储 SQL 关系型数据库
MySQL的事务隔离级别
【10月更文挑战第17天】MySQL的事务隔离级别
159 43
|
3月前
|
关系型数据库 MySQL
mysql事务特性
原子性:一个事务内的操作统一成功或失败 一致性:事务前后的数据总量不变 隔离性:事务与事务之间相互不影响 持久性:事务一旦提交发生的改变不可逆

推荐镜像

更多