#用来验证用户是否有权限登陆的中间件 class AuthenticationMiddle(MiddlewareMixin): def process_request(self, request): url_path = request.path #如果不在请求在白名单里 if url_path not in exclued_path: #如果未登陆,则调转到登陆页面,将请求的url作为next参数 # if not request.user.is_authenticated: if not request.session.get("user"): # return redirect("/login/?next={url_path}".format(url_path=url_path)) return JsonResponse({'code': -1, 'msg': 'login is failed2222'}) #如果已经登陆,则通过 else: pass
File "D:\app\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 36, in <module> raise ImproperlyConfigured('mysqlclient 1.4.0 or newer is required; you have %s.' % Database.__version__) django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.10.1.
class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=64) email = models.EmailField()
class Author(models.Model): name = models.CharField(max_length=32) age = models.SmallIntegerField() # 一对一,意思为一个作者对应一个作者详情 au_detail = models.OneToOneField("AuthorDetail", on_delete=models.CASCADE)
# 清空独孤九剑关联的所有作者 book = models.Book.objects.filter(title="菜鸟教程").first() book.authors.clear()
对于 ForeignKey 对象,这个方法仅在 null=True(可以为空)时存在。
ORM 查询
一对多
查询主键为 10 的书籍的出版社所在的城市(正向)。
1 2 3 4
book = models.Book.objects.filter(pk=10).first() res = book.publish.city print(res, type(res)) return HttpResponse("ok")
查询明教出版社出版的书籍名(反向)。
1 2 3 4 5 6
pub = models.Publish.objects.filter(name="明教出版社").first() # pub.book_set.all():取出书籍表的所有书籍对象,在一个 QuerySet 里,遍历取出一个个书籍对象。 res = pub.book_set.all() for i in res: print(i.title) return HttpResponse("ok")
一对一
查询令狐冲的电话(正向)
正向:对象.属性 (author.au_detail) 可以跳转到关联的表(作者详情表)
1 2 3 4
author = models.Author.objects.filter(name="令狐冲").first() res = author.au_detail.tel print(res, type(res)) return HttpResponse("ok")
查询所有住址在黑木崖的作者的姓名(反向)。
1 2 3 4
addr = models.AuthorDetail.objects.filter(addr="黑木崖").first() res = addr.author.name print(res, type(res)) return HttpResponse("ok")
book = models.Book.objects.filter(title="菜鸟教程").first() res = book.authors.all() for i in res: print(i.name, i.au_detail.tel) return HttpResponse("ok")
查询任我行出过的所有书籍的名字(反向)。
1 2 3 4 5
author = models.Author.objects.filter(name="任我行").first() res = author.book_set.all() for i in res: print(i.title) return HttpResponse("ok")
基于双下划线的跨表查询
正向:属性名称__跨表的属性名称
反向:小写类名__跨表的属性名称
一对多
正向:查询菜鸟出版社出版过的所有书籍的名字与价格。
1 2
# publish__name 跨表中的name res = models.Book.objects.filter(publish__name="菜鸟出版社").values_list("title", "price")
[root@VM-24-13-centos home]# uname -a Linux VM-24-13-centos 3.10.0-1160.11.1.el7.x86_64 #1 SMP Fri Dec 18 16:34:56 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
直接部署
分别为下载,解压go
1 2 3 4 5 6 7 8
[root@VM-24-13-centos /]# cd home [root@VM-24-13-centos home]# wget https://dl.google.com/go/go1.20.4.linux-amd64.tar.gz [root@VM-24-13-centos home]# tar -zxvf go1.20.4.linux-amd64.tar.gz [root@VM-24-13-centos bin]# pwd /home/go/bin [root@VM-24-13-centos bin]# ./go version go version go1.20.4 linux/amd64
PS E:\proj\gowork\study-gozero-demo\mall\user\rpc> go run user.go Starting rpc server at 0.0.0.0:8080...
启动user api,用来登录返回token
1 2
PS E:\proj\gowork\study-gozero-demo\mall\user\api> go run .\user.go Starting server at 0.0.0.0:8888.
启动order api,对外的接口
1 2 3
PS E:\proj\gowork\study-gozero-demo\mall\order\api> go run .\order.go Starting server at 0.0.0.0:8889... {"@timestamp":"2023-07-30T16:03:50.226+08:00","cal
// userdellogic.go func(l *UserDelLogic) UserDel(req *types.UserDelReq) (resp *types.UserDelRes, err error) { // todo: add your logic here and delete this line
OrderAddRes { Code int `json:"code"` Messsage string `json:"message"` } )
// 在哪个服务头上加这个验证,就是需要jwt鉴权 @server( jwt: Auth ) service order { @handler orderAdd post /api/order/OrderAdd (OrderAddReq) returns (OrderAddRes) }
service order { @handler getOrder get /api/order/get/:id (OrderReq) returns (OrderReply) } // 在哪个服务头上加这个验证,就是需要jwt鉴权 @server( jwt: Auth ) service order { @handler orderAdd post /api/order/OrderAdd (OrderAddReq) returns (OrderAddRes) }
service order { @handler getOrder get /api/order/get/:id (OrderReq) returns (OrderReply) }
生成order.api代码
1
PS E:\proj\gowork\study-gozero-demo\mall\order\api> goctl api go -api order.api -dir .
E:\proj\gowork>mkdir go-zero-demo E:\proj\gowork>cd go-zero-demo E:\proj\gowork\go-zero-demo>go mod init go-zero-demo go: creating new go.mod: module go-zero-demo E:\proj\gowork\go-zero-demo>goctl api new greet Done. E:\proj\gowork\go-zero-demo>go mod tidy
OrderReply { Id string `json:"id"` Name string `json:"name"` } ) service order { @handler getOrder get /api/order/get/:id (OrderReq) returns (OrderReply) }
生成order服务,非rpc
1
PS E:\proj\gowork\study-gozero-demo\mall\order\api> goctl api go -api order.api -dir .
E:\proj\gowork\study-gozero-demo\mall\user\rpc> go run .\user.go
启动order api
1 2 3
PS E:\proj\gowork\study-gozero-demo\mall\order\api> go run order.go Starting server at 0.0.0.0:8888... {"@timestamp":"2023-07-26T16:36:58.057+08:00","caller":"stat/usage.go:61","content":"CPU: 0m, MEMORY: Alloc=3.2Mi, TotalAlloc=6.1Mi, Sys=17.9Mi, NumGC=3","level":"stat"}
coll := toDB.Collection("users") objId, err := coll.InsertOne(context.TODO(), doc) fmt.Println(objId) if err != nil { return } fmt.Println("新增成功") var one Student filter := bson.D{{"id", 1}} var ctx context.Context var cancel func() ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) defer cancel() err = coll.FindOne(ctx, filter).Decode(&one) if err == mongo.ErrNoDocuments { // Do something when no record was found fmt.Println("record does not exist") } elseif err != nil { log.Fatal(err) } fmt.Println(one)
}
运行结果
1 2 3 4 5 6 7
PS E:\proj\gowork\studyMongoDb> go run .\main.go <nil> sussces &{ObjectID("64ae992a5063fc95642035ed")} 新增成功 {1 刘刘 18} PS E:\proj\gowork\studyMongoDb>
PS E:\proj\gowork\studyMongoDb> go run .\main.go [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] POST /UserAdd --> example.com/studyMongoDb/api.UserAdd (3 handlers) [GIN-debug] GET /UserList --> example.com/studyMongoDb/api.UserList (3 handlers) [GIN-debug] POST /UserEditOne --> example.com/studyMongoDb/api.UserEditOne (3 handlers) [GIN-debug] POST /UserDelete --> example.com/studyMongoDb/api.UserDelete (3 handlers) [GIN-debug] GET /UserQuery/:key --> example.com/studyMongoDb/routers.InitRouter.func1 (3 handlers) [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value. Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details. [GIN-debug] Listening and serving HTTP on :8000