day78 面试程序

程序

简单的web
import socket
from threading import Thread
server = socket.socket()
server.bind(('0.0.0.0',8001))
server.listen()
def communication(conn):
    client_msg = conn.recv(1024).decode('utf-8')
    # print(client_msg)
    path = client_msg.split('\r\n')[0].split(' ')[1]
    print(path)
    #针对不同的请求路径,返回不同的文件
    if path =='/':
        conn.send(b'HTTP/1.1 200 ok \r\nk1:v1\r\n\r\n')
        # conn.send(b'who are you?')
        with open('01 index2.html', 'rb') as f:
            data = f.read()
        conn.send(data)
        conn.close()

while 1:
    conn, add = server.accept()
    t = Thread(target=communication,args=(conn,))
    t.start()
保持连接
#和咱们学的socketserver那个模块很像啊
httpd = make_server('127.0.0.1', 8001, application)	  bind connect 连接地址  
print('Serving HTTP on port 8001...')
# 开始监听HTTP请求:
httpd.serve_forever()		

jinja2

from wsgiref.simple_server import make_server
from jinja2 import Template


def index():
    with open("index2.html", "r",encoding='utf-8') as f:
        data = f.read()
    template = Template(data)  # 生成模板文件
    ret = template.render({"name": "于谦", "hobby_list": ["烫头", "泡吧"]})  # 把数据填充到模板里面
    return [bytes(ret, encoding="utf8"), ]


# 定义一个url和函数的对应关系
URL_LIST = [
    ("/index/", index),
]

def run_server(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])  # 设置HTTP响应的状态码和头信息
    url = environ['PATH_INFO']  # 取到用户输入的url
    func = None  # 将要执行的函数
    for i in URL_LIST:
        if i[0] == url:
            func = i[1]  # 去之前定义好的url列表里找url应该执行的函数
            break
    if func:  # 如果能找到要执行的函数
        return func()  # 返回函数的执行结果
    else:
        return [bytes("404没有该页面", encoding="utf8"), ]


if __name__ == '__main__':
    httpd = make_server('', 8000, run_server)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()

URL 路由分发就是当前的 枚举的那一套路

自定义原生sql
def auth(username,password):
    import pymysql
    conn = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123',
        database='day53',
        charset='utf8'
    )
    print('userinfo',username,password)
    cursor = conn.cursor(pymysql.cursors.DictCursor)

    sql = 'select * from userinfo where username=%s and password=%s;'
    res = cursor.execute(sql, [username, password])

    if res:
        return True

formset .py

from django.forms.models import modelformset_factory
from django import forms
class StudyRecordDetialModelForm(forms.ModelForm):
    class Meta:
        model = models.StudentStudyRecord
        # fields = '__all__'
        fields = ['score','homework_note']
class StudyRecordDetialView2(View):
      def get(self,request,class_record_id):
          all_study_record = models.StudentStudyRecord.objects.filter(  # 找到这个课程记录的所有学生记录
                          classstudyrecord=class_record_id,
                      )
          form_set_obj = modelformset_factory(model=models.StudentStudyRecord,form=StudyRecordDetialModelForm)
                    # 哪张表(model)来使用modelformset  使用这张表来加工表的时候用的哪个modermform(from)
          formset = form_set_obj(queryset = all_study_record)   #使用all_study_record来加工query记录
                    # 来加工modermform的哪些数据,通过queryset来指定
          return render(request, 'student/study_record_detail.html', { 'formset': formset })


      def post(self,request,class_record_id):
          all_study_record = models.StudentStudyRecord.objects.filter(  # 找到这个课程记录的所有学生记录
              classstudyrecord=class_record_id,
          )
          form_set_obj = modelformset_factory(model=models.StudentStudyRecord, form=StudyRecordDetialModelForm,extra=0)
          # 哪张表(model)来使用modelformset  使用这张表来加工表的时候用的哪个modermform(from)
          formset = form_set_obj(request.POST)  # 使用all_study_record来加工query记录
          # 来加工modermform的哪些数据,通过queryset来指定
          if formset.is_valid():
              formset.save()
          else:
              print(formset.errors)
          #
          # return redirect(reverse('study_record',args=(class_record_id,)))
          return self.get(request,class_record_id)
          # return request.get(request,class_record_id)

formset.html

   {{ formset.management_form }}        {# 类似于csrf认识的标识符      #}
      <table class="table table-bordered">
                    <thread>
                        <tr>
                            <th>姓名</th>
                            <th>考勤</th>
                            <th>作业成绩</th>
                            <th>作业评语</th>
                        </tr>
                    </thread>
                    <tbody>
                        {% for form in formset %}   {# formset 就包括了一条条记录#}
                            <tr>
                                {{ form.id }}       {# pk值#}
                                <td>{{ form.student }}</td>  {#默认会自动生成下拉框 ,如果不让他渲染,#}
                                                        {#那么需要使用form.instance.student.这是form对象原值,原来的数据#}

                            <td>{{ form.get_record_display }}</td>
{#                            <td>{{ form.instance.get_record_display }}</td>#}
                            <td>{{ form.score }}</td>
                            <td>{{ form.homework_note }}</td>
                            </tr>
posted @ 2019-06-24 23:05  learnacode  阅读(125)  评论(0编辑  收藏  举报