Python+Django+小程序API的编写

<p>在学习这个之前,首先要求是你们会Django框架的基础之上,如果不会可以<a href='https://blog.songshao.site/single/10007/'>点击这里</a>学习有关Django框架的一些使用方案,在下面我将会讲出有关api的简单编写和json数据处理过程。</p> <p>api结构主要包括请求链接,入参,Django的业务逻辑处理,返回参数。一般情况下尽量使用POST请求,数据比较安全。</p> <ol> <li><p>Django的业务逻辑</p> <ol> <li><p>urls的编写</p> <p>两种方法的原因是1.7以前不支持path来编写</p> <pre><code class='language-python' lang='python'>Django2.0.4可以使用以下方法 from django.urls import path urlpatterns = [ path(&#39;depot/&#39;, get_depot), path(&#39;depot_list/&#39;, get_depot_list) ] Django1.7.0可以使用以下方法 from django.conf.urls import url urlpatterns = [ url(r&#39;depot/$&#39;, get_depot), url(r&#39;depot_list/$&#39;, get_depot_list) ] </code></pre> </li> <li><p>models创建</p> <p>就举个简单的栗子吧,这样更加明确直白,这三个表个栗子,可以解决以后的多表联合查询问题。</p> <pre><code class='language-python' lang='python'># 停车场表 class TB_DEPOT(models.Model): DE_ID = models.CharField(max_length=18, verbose_name=&quot;停车场编码&quot;, primary_key=True) NAME = models.CharField(max_length=11, verbose_name=&quot;停车场名称&quot;) ADDRESS = models.CharField(max_length=64, verbose_name=&quot;停车场地址&quot;) LATITUDE = models.CharField(max_length=18, verbose_name=&quot;坐标(纬度)&quot;) LONGITUDE = models.CharField(max_length=18, verbose_name=&quot;坐标(经度)&quot;) COST_1 = models.CharField(max_length=6, verbose_name=&quot;停车费用_1&quot;) COST_2 = models.CharField(max_length=6, verbose_name=&quot;停车费用_2&quot;,null=True) MAN_COST = models.CharField(max_length=6, verbose_name=&quot;日最高消费&quot;,null=True) FREE_TIME = models.CharField(max_length=6, verbose_name=&quot;免费时长&quot;,null=True) MODE_PAY = models.CharField(max_length=11, verbose_name=&quot;支付方式&quot;) START_DATE = models.TimeField(verbose_name=&quot;营业开始时间&quot;) END_DATE = models.TimeField(verbose_name=&quot;营业结束时间&quot;) STATE = models.IntegerField(verbose_name=&quot;停车场状态&quot;) IMAGE_1 = models.ImageField(verbose_name=&quot;图片一&quot;, upload_to=image_upload_to) IMAGE_2 = models.ImageField(verbose_name=&quot;图片二&quot;, null=True, upload_to=image_upload_to) IMAGE_3 = models.ImageField(verbose_name=&quot;图片三&quot;, null=True, upload_to=image_upload_to) IMAGE_4 = models.ImageField(verbose_name=&quot;图片四&quot;, null=True, upload_to=image_upload_to) BUSI_ID = models.ForeignKey(TB_BUSINESSMAN, verbose_name=&quot;商户编码&quot;, on_delete=models.CASCADE) def __str__(self): return self.DE_ID class Meta: db_table = &quot;TB_DEPOT&quot; verbose_name = &#39;停车场&#39; verbose_name_plural = verbose_name # 预约表(TB_APPOINTMENT) class TB_APPOINTMENT(models.Model): APPO_ID = models.CharField(max_length=18, verbose_name=&quot;预约编码&quot;, primary_key=True) USER_ID = models.CharField(max_length=18, verbose_name=&quot;预约人编码&quot;) DATE = models.DateField(verbose_name=&#39;预约时间&#39;) PL_NUM = models.CharField(max_length=10, verbose_name=&#39;预约车牌&#39;, default=&#39;&#39;) APPO_TIME = models.CharField(max_length=4, verbose_name=&quot;预约时长&quot;) COST = models.CharField(max_length=4, verbose_name=&quot;预约费用&quot;) STATE = models.IntegerField(verbose_name=&quot;预约付款状态&quot;) APPO_STATE = models.IntegerField(verbose_name=&#39;预约过期状态&#39;, default=&#39;1&#39;) OUTPUT = models.IntegerField(verbose_name=&#39;是否入场&#39;, default=&#39;0&#39;) DEPOT = models.ForeignKey(TB_DEPOT, verbose_name=&quot;停车场编码&quot;, on_delete=models.CASCADE) def __str__(self): return self.APPO_ID class Meta: db_table = &quot;TB_APPOINTMENT&quot; verbose_name = &#39;预约&#39; verbose_name_plural = verbose_name # 用户表(TB_USER) class TB_USER(models.Model): OPEN_ID = models.CharField(max_length=64, verbose_name=&#39;微信唯一标识&#39;) USER_ID = models.CharField(max_length=32, verbose_name=&#39;用户编码&#39;) PHONE = models.CharField(max_length=11, verbose_name=&#39;用户手机号&#39;, null=True, default=&#39;&#39;) USER_NAME = models.CharField(max_length=32, verbose_name=&#39;用户微信名称&#39;) USER_STATE = models.IntegerField(verbose_name=&#39;用户状态&#39;) def __str__(self): return self.OPEN_ID class Meta: db_table = &quot;TB_USER&quot; verbose_name = &#39;用户&#39; verbose_name_plural = verbose_name </code></pre> </li> <li><p>api方法的编写</p> <p>先看一个简单的查询业务案例,停车场表信息查询</p> <pre><code class='language-python' lang='python'>from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt #请求参数设置 #http://localhost:8000/Api/depot/ # 入参 无 # 返回json数据 def get_depot(request): if request.method == &#39;GET&#39;: try: data = {} depot = TB_DEPOT.objects.values() data[&#39;depot&#39;] = list(depot) print(data[&#39;depot&#39;]) return JsonResponse({&#39;success&#39;: True, &#39;data&#39;: data[&#39;depot&#39;]}) except Exception as e: return JsonResponse({&#39;success&#39;: False, &#39;data&#39;: str(e)}) </code></pre> <p>主要问题就是如何把把QuerySet,数据转化成json数据,也就是Python中的字典,根据<code>depot = TB_DEPOT.objects.values()</code>获取到数据对象,然后使用下面这种简单的方法来把数据转化成json数据,<code>data[&#39;depot&#39;] = list(depot)</code>,这种方法给大家解释一下他就是把获取到的数据对象转化成list对象,然后反身存储到data[&#39;depot&#39;]中,完成一个简单的转化。</p> <p>下面这个栗子稍微有点复杂通过请求链接传参,进行获取数据,进行数据查询,拼接,返回json对象。</p> <pre><code class='language-python' lang='python'># 用户预约信息查询 根据用户唯一标识openid进行查询 # 请求示例 # 请求示例:http://localhost:8000/Api/get_appo_over/?openId=****** # 入参设置,需要进行openid标识传入 # 可选参数:STATE、PPO_STATE、OUTPUT # 返回用户预约的记录 def get_appo_over(request): data = {} if request.method == &#39;GET&#39;: openid = request.GET.get(&#39;openId&#39;) state = request.GET.get(&#39;state&#39;) output = request.GET.get(&#39;output&#39;) appo_state = request.GET.get(&#39;appo_state&#39;) try: userid = TB_USER.objects.get(OPEN_ID=openid).USER_ID print(userid) appo = {} if state: appo = TB_APPOINTMENT.objects.filter(Q(USER_ID=userid) &amp; Q(STATE=state)) elif appo_state: appo = TB_APPOINTMENT.objects.filter(Q(USER_ID=userid) &amp; Q(APPO_STATE=appo_state)) elif output: appo = TB_APPOINTMENT.objects.filter(Q(USER_ID=userid) &amp; Q(OUTPUT=output)) else: appo = TB_APPOINTMENT.objects.filter(Q(USER_ID=userid)) data[&#39;appo&#39;] = list(appo.values()) i = 0 for a in appo: print(a.DEPOT.DE_ID) depot = TB_DEPOT.objects.filter(DE_ID=a.DEPOT.DE_ID).values() data[&#39;depot&#39;] = list(depot) print(data[&#39;depot&#39;]) data[&#39;appo&#39;][i].update(data[&#39;depot&#39;][0]) i = i + 1 return JsonResponse({&#39;success&#39;: True, &#39;data&#39;: data[&#39;appo&#39;]}) except Exception as e: return JsonResponse({&#39;success&#39;: False, &#39;data&#39;: 0}) </code></pre> <p>这个接口,主要是进行预约和相对应的停车场进行查询简单解释一下一些语句的用途</p> <p><code>openid = request.GET.get(&#39;openId&#39;)</code></p> <p>使用该代码来获取请求链接中的参数;</p> <pre><code class='language-python' lang='python'> i = 0 for a in appo: print(a.DEPOT.DE_ID) depot = TB_DEPOT.objects.filter(DE_ID=a.DEPOT.DE_ID).values() data[&#39;depot&#39;] = list(depot) print(data[&#39;depot&#39;]) data[&#39;appo&#39;][i].update(data[&#39;depot&#39;][0]) i = i + 1 </code></pre> <p>这块代码主要是对预约记录进行解析出来,根据对应的a.DEPOT.DE_ID标识去进行停车场查询,将得到的数据转化,然后拼接到appo数据中,因为data[&#39;depot&#39;]和data[&#39;appo&#39;]都属于是dict类型的对象,可以使用update直接把数据更新到另一个里面注意的是如果直接更新,相同索引的值都会被替换掉,所以使用之前先对数据进行处理。</p> </li> <li><p>小程序端的请求方法</p> <pre><code class='language-javascript' lang='javascript'>var that = this wx.request({ url: &#39;http://127.0.0.1:8000/Api/get_appo_over/?openId=&#39; + app.gloabData.openid + &#39;&amp;state=0&#39;, method: &#39;GET&#39;, // url: &#39;https://api.songshao.site/Api/get_appo_over/?openId=&#39; + app.gloabData.openid + &#39;&amp;state=0&#39;, method: &#39;GET&#39;, header: { &#39;content-type&#39;: &#39;application/json,charset=utf-8&#39; }, success: function (res) { console.log(res.data.data) if (res.data.data.length == 0) { that.setData({ num: 0 }) } else { that.setData({ num: 1, appo: res.data.data, }) } }, fail: function (res) { wx.showToast({ title: &#39;服务器开了小差,下拉刷新一下&#39;, icon: &#39;waring&#39;, duration: 3000 }) } }) </code></pre> <p>&nbsp;</p> <p>小程序使用wx.request来请求api,在url中编写链接地址和对应的参数,请求method一般尽量使用post,请求头设置 header: { &#39;content-type&#39;: &#39;application/json,charset=utf-8&#39; },成功之后返回数据处理请求成功数据如下:</p> <pre><code class='language-json' lang='json'>{&quot;success&quot;: true, &quot;data&quot;: [{&quot;APPO_ID&quot;: &quot;684407&quot;, &quot;USER_ID&quot;: &quot;8208225&quot;, &quot;DATE&quot;: &quot;2018-12-25&quot;, &quot;PL_NUM&quot;: &quot;\u9655A88888&quot;, &quot;APPO_TIME&quot;: &quot;10&quot;, &quot;COST&quot;: &quot;0.5&quot;, &quot;STATE&quot;: 1, &quot;APPO_STATE&quot;: 1, &quot;OUTPUT&quot;: 0, &quot;DEPOT_id&quot;: &quot;20181215002&quot;, &quot;DE_ID&quot;: &quot;20181215002&quot;, &quot;NAME&quot;: &quot;\u5c1a\u54c1\u7f8e\u5730\u57ce\u4e8c\u671f&quot;, &quot;ADDRESS&quot;: &quot;\u9655\u897f\u7701\u897f\u5b89\u5e02\u96c1\u5854\u533a\u9526\u4e1a\u8def92\u53f7&quot;, &quot;LATITUDE&quot;: &quot;34.34627&quot;, &quot;LONGITUDE&quot;: &quot;108.93984&quot;, &quot;COST_1&quot;: &quot;5&quot;, &quot;COST_2&quot;: &quot;6&quot;, &quot;MAN_COST&quot;: &quot;50&quot;, &quot;FREE_TIME&quot;: &quot;0.5&quot;, &quot;MODE_PAY&quot;: &quot;\u7535\u5b50\u652f\u4ed8&quot;, &quot;START_DATE&quot;: &quot;00:00:00&quot;, &quot;END_DATE&quot;: &quot;23:59:00&quot;, &quot;IMAGE_1&quot;: &quot;index/static/upload_image/47735b874b494483b1ab1149b1b6d84d/\u5c1a\u54c1.jpg&quot;, &quot;IMAGE_2&quot;: &quot;index/static/upload_image/d03235beb44548de9cab02041ba2d511/\u5c1a\u54c1.jpg&quot;, &quot;IMAGE_3&quot;: &quot;index/static/upload_image/14545c2c9f4a4e2ebf392a3fe04bc1af/\u5c1a\u54c1.jpg&quot;, &quot;IMAGE_4&quot;: &quot;index/static/upload_image/4bb82db280584fa6a6e4f91fde65f7e5/\u5c1a\u54c1.jpg&quot;, &quot;BUSI_ID_id&quot;: &quot;20181215001&quot;}, {&quot;APPO_ID&quot;: &quot;9276129&quot;, &quot;USER_ID&quot;: &quot;8208225&quot;, &quot;DATE&quot;: &quot;2018-12-25&quot;, &quot;PL_NUM&quot;: &quot;\u9655E88888&quot;, &quot;APPO_TIME&quot;: &quot;10&quot;, &quot;COST&quot;: &quot;0.5&quot;, &quot;STATE&quot;: 1, &quot;APPO_STATE&quot;: 0, &quot;OUTPUT&quot;: 0, &quot;DEPOT_id&quot;: &quot;20181215002&quot;, &quot;DE_ID&quot;: &quot;20181215002&quot;, &quot;NAME&quot;: &quot;\u5c1a\u54c1\u7f8e\u5730\u57ce\u4e8c\u671f&quot;, &quot;ADDRESS&quot;: &quot;\u9655\u897f\u7701\u897f\u5b89\u5e02\u96c1\u5854\u533a\u9526\u4e1a\u8def92\u53f7&quot;, &quot;LATITUDE&quot;: &quot;34.34627&quot;, &quot;LONGITUDE&quot;: &quot;108.93984&quot;, &quot;COST_1&quot;: &quot;5&quot;, &quot;COST_2&quot;: &quot;6&quot;, &quot;MAN_COST&quot;: &quot;50&quot;, &quot;FREE_TIME&quot;: &quot;0.5&quot;, &quot;MODE_PAY&quot;: &quot;\u7535\u5b50\u652f\u4ed8&quot;, &quot;START_DATE&quot;: &quot;00:00:00&quot;, &quot;END_DATE&quot;: &quot;23:59:00&quot;, &quot;IMAGE_1&quot;: &quot;index/static/upload_image/47735b874b494483b1ab1149b1b6d84d/\u5c1a\u54c1.jpg&quot;, &quot;IMAGE_2&quot;: &quot;index/static/upload_image/d03235beb44548de9cab02041ba2d511/\u5c1a\u54c1.jpg&quot;, &quot;IMAGE_3&quot;: &quot;index/static/upload_image/14545c2c9f4a4e2ebf392a3fe04bc1af/\u5c1a\u54c1.jpg&quot;, &quot;IMAGE_4&quot;: &quot;index/static/upload_image/4bb82db280584fa6a6e4f91fde65f7e5/\u5c1a\u54c1.jpg&quot;, &quot;BUSI_ID_id&quot;: &quot;20181215001&quot;}]} </code></pre> <p>首先需要说明小程序请求之后会把json数据默认存放方到data里面,这块本省还有一个data,所以定位时就需要用res.data.data定位数据,像这个json数据有两条,在页面显示时可以用for循环输出数据</p> <pre><code class='language-html' lang='html'>&lt;view class=&#39;content_view&#39; wx:for=&#39;{{appo}}&#39; wx:key&gt; &lt;view class=&#39;header&#39;&gt; &lt;text class=&#39;l_text&#39;&gt;{{item.DATE}}&lt;/text&gt; &lt;text class=&#39;r_text&#39;&gt;未进场&lt;/text&gt; &lt;/view&gt; &lt;view class=&#39;header_content&#39;&gt; &lt;view class=&#39;header_text&#39;&gt; &lt;text&gt;{{item.NAME}}停车场&lt;/text&gt; &lt;/view&gt; &lt;view class=&#39;text_view&#39;&gt; &lt;image class=&#39;image_style&#39; src=&#39;../../resource/image/ding_wei_1.png&#39;/&gt; &lt;text class=&#39;text_view_text&#39;&gt;{{item.ADDRESS}}&lt;/text&gt; &lt;/view&gt; &lt;view class=&#39;text_view&#39;&gt; &lt;image class=&#39;image_style&#39; src=&#39;../../resource/image/car.png&#39;/&gt; &lt;text class=&#39;text_view_text&#39;&gt;预约车牌为:{{item.PL_NUM}}&lt;/text&gt; &lt;/view&gt; &lt;view class=&#39;text_view&#39;&gt; &lt;image class=&#39;image_style&#39; src=&#39;../../resource/image/time.png&#39;/&gt; &lt;text class=&#39;text_view_text&#39;&gt;剩余时长:{{item.APPO_TIME}}&lt;/text&gt; &lt;/view&gt; &lt;button class=&#39;btn&#39;&gt;续费&lt;/button&gt; &lt;/view&gt; &lt;/view&gt; </code></pre> <p>在循环中可以通过定义的数据对象appo,去循环,因为循环使用的是它的array(),因为json对象有两条所以循环两次,输出,每次遍历数组对象是可以使用item.属性名,来获取相应的数据,显示结果如下图所示</p> <p><img src='/static/upload/xiaochengx_list1.png' alt='xiaochengx_list1' referrerPolicy='no-referrer' /></p> <p>如果出现这种结果就说明你的小程序成功了!</p> </li> </ol> </li> </ol>