qq_42861962 2021-07-12 21:29 采纳率: 0%
浏览 13

上次说添加代码,这次我添加了完整的代码,有知道的请过目,谢!

今天做的是python的学生信息表
最近总是在urrlib.request.urlopen上面出错,我真的不晓得该怎么使用这个
有人告诉我刚开始容易在urrlib里面出错,先采取requests来操作
那么urrlib.request.urlopen怎样用requests来替换?
在我的增加学生信息里面的话语是这样的:
st = st.encode()
content = urllib.request.urlopen(url + "?opt = insert", st)
还有人说我的urllib.request.urlopen()的用法都用错了。
这个是服务器的代码

import flask
import sqlite3
import json

app = flask.Flask(__name__)

class StudentDB:
    def openDB(self):
        self.con = sqlite3.connect("students.db")
        self.cursor = self.con.cursor()

    def closeDB(self):
        self.con.commit()
        self.con.close()

    def initTable(self):
        res = {}
        try:
            self.cursor.execute("create table students (No varchar(16) prinmary key , Namevarchar(16) Sex varchar(8) Age int)")
            res["msg"] = "OK"
        except Exception as err:
            res["msg"] = str(err)
        return res
    def insertRow(self,No,Name,Sex,Age):
        res = {}
        try:
            self.cursor.execute("insert into students (No,Name,Sex,Age) values(????)", (No, Name, Sex, Age))
            res["msg"] = "OK"
        except Exception as err:
            res["msg"] = str(err)
        return res
    def deleteRow(self):
        res = {}
        try:
            self.cursor.execute("delete from students where No = ?" , (No,))
            res["msg"] = "OK"
        except Exception as err:
             res["msg"] = str(err)
        return res
    def selectRows(self):
        res = {}
        try:
            data = []
            self.cursor.execute("select * from students order by No")
            rows = self.cursor.fetchall()
            for row in rows:
                d = {}
                d["No"] = row[0]
                d["Name"] = row[1]
                d["Sex"] = row[2]
                d["Age"] = row[3]
                data.append(d)
            res["msg"] = "Ok"
            res["data"] = data
        except Exception as err:
            res["msg"] = str(err)
        return res

@app.route("/" , methods=["GET","POST"])
def process():
    opt = flask.request.values.get("opt") if "opt" in flask.request.values else ""
    res = {}
    db = StudentDB()
    db.openDB()
    if opt == "init":
        res = db.initTable()
    elif opt == "insert":
        No = flask.request.values.get("No") if "No" in flask.request.values else ""
        Name = flask.request.values.get("Name") if "Name" in flask.request.values else ""
        Sex = flask.request.values.get("Sex") if "Sex" in flask.request.values else ""
        Age = flask.request.values.get("Age") if "Age" in flask.request.values else ""
        res = db.insertRow(No, Name, Sex, Age)
    elif opt =="delete":
        No = flask.request.values.get("No") if "No" in flask.request.values else ""
        res = db.deleteRow(No)
    else:
        res = db.selectRows()
    db.closeDB()
    return json.dumps(res)
if __name__ == "__main__":
    app.run()

这个是客户端的代码

import urllib.request
import json
import requests

class Student:
    def __init__(self, No, Name, Sex, Age):
        self.No = No
        self.Name = Name
        self.Sex = Sex
        self.Age = Age

    def show(self):
        print("%-16s %-16s %-8s %-4d" % (self.No, self.Name, self.Sex, self.Age))

students = []
url = "http://127.0.0.1:5000"

def listStudents():
    global students
    print("%-16s %-16s %-8s %-4s" % ("No","Name","Sex","Age"))
    for s in students:
        s.show()
def insertStudent(s):
    global students
    i = 0
    while(i < len(students) and s.No > students[i].No):
        i = i + 1
    if(i < len(students) and s.No == students[i].No):
        print(s.No + "already exists")
        return False
    students.insert(i,s)
    return True
def deleteRow():
    global students
    No = input("No=")
    if(No != ""):
        for i in range(len(students)):
            if(students[i].No == No):
                st = ""
                try:
                    st = "No=" + urllib.request.quote(No)
                    st = st.encode()
                    content = urllib.request.urlopen(url + "?opt=delete", st)
                    st = content.readline()
                    st = json.loads(st.decode())
                    st = st["msg"]
                except Exception as exp:
                    st = str(exp)
                if(st == "OK"):
                    del students[i]
                    print("删除成功")
                else:
                    print(st)
                break
def insertRow():
    No = input("No=")
    Name = input("Name=")
    while True:
        Sex = input("Sex=")
        if(Sex == "男" or Sex == "女"):
            break
        else:
            print("Sex is not vaild")
    Age = input("Age=")
    if(Age == ""):
        Age = 0
    else:
        Age = int(Age)
    if No != "" and Name != "":
        s = Student(No,Name,Sex,Age)
        for x in students:
            if(x.No == No):
                print(No + "already exists")
                return
        st = ""
        try:
            st = "No=" + urllib.request.quote(No) + "&Name=" + urllib.request.quote(Name) + "&Sex=" + urllib.request.quote(Sex) + "&Age=" + str(Age)
            st = st.encode()
            content = urllib.request.urlopen(url + "?opt = insert", st)
            st = content.read()
            st = json.loads(st.decode())
            st = st["msg"]
        except Exception as exp:
            st = str(exp)
        if (st == "OK"):
            insertStudent(s)
            print("增加成功")
        else:
            print(st)
    else:
        print("学号、姓名不能为空")
def initialize():
    st = ""
    try:
        content = urllib.request.urlopen(url + "?opt = init")
        st = content.read()
        st = json.loads(st.decode())
        st = st["msg"]
    except Exception as exp:
        st = str(exp)
    if(st == "OK"):
        print("初始成功")
    else:
        print(st)
    return st

def readStudents():
    global students
    try:
        students.clear()
        content = urllib.request.urlopen(url)
        data = b""
        while True:
            buf = content.read(1024)
            if(len(buf) > 0):
                data = data + buf
            else:
                break
        data = data.decode()
        data = json.loads(data)
        if data["msg"] == "OK":
            data = data["data"]
            for d in data:
                s = Student(d["No"],d["Name"],d["Sex"],d["Age"])
                students.append(s)
    except Exception as exp:
        print(exp)
try:
    readStudents()

    while True:
        print("")
        print("***学生名单***")
        print("0.初始化学生表")
        print("1.查看学生列表")
        print("2.增加学生记录")
        print("3.删除学生记录")
        print("4.退出这个程序")
        s = input("请选择(0,1,2,3,4):")
        if(s == "0"):
            initialize()
        elif(s == "1"):
            listStudents()
        elif(s == "2"):
            insertRow()
        elif(s == "3"):
            deleteRow()
        elif(s == "4"):
            break
except Exception as exp:
    print(exp)

请过目,谢!

  • 写回答

2条回答 默认 最新

  • cnkeysky 2021-07-12 22:30
    关注

    opt=insert,=之间不要加空格看看

    评论

报告相同问题?

问题事件

  • 创建了问题 7月12日

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答