如何通过pycharm写一些python的api接口在webservice下调用

感谢温狗的帮助,困扰很久的问题终于解决

掌握django基本语法即可
只需要在views.py下编辑

from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
import word2vec
import  json
#输入a和b返回a+b
class TestAPIView(APIView):
    def get(self, request):
        a=int(request.query_params['a'])
        b=int(request.query_params['b'])
        res = {
    
    "a":a,"b":b,"sum":a+b}
        return HttpResponse(json.dumps(res),content_type="application/json,charset=utf-8")
#输入a和b返回a+b
class TestAPIViewByPost(APIView):
    def post(self, request):
        req = json.loads(request.body.decode())
        a = req.get('a')
        b = req.get('b')
        res = {
    
    "a":a,"b":b,"sum":a+b}
        return HttpResponse(json.dumps(res),content_type="application/json,charset=utf-8")

#word2vec的api调用,传入一个word返回一个向量
class TestAPIView2(APIView):
    def get(self, request):
        a = str(request.query_params['a'])
        model = word2vec.load("/Users/jianghuiwen/Desktop/text8.txt")


        # result = {'a': a, 'b': b}
        # js = json.dumps(result)
        # return Response(js)
        b=model[a]
        return Response('{}'.format(b))






再在urls.py下编写

"""djangoProject2 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path
from rest_framework.views import APIView

from rest_framework.response import Response

from app01.views import TestAPIView
from app01.views import TestAPIView2
from app01.views import TestAPIViewByPost
urlpatterns = [
    # path('test/', TestAPIView.as_view()),
    path('word2vec/', TestAPIView2.as_view()),
    path('add/', TestAPIView.as_view()),
    path('posttest', TestAPIViewByPost.as_view())
]


如此我们即可调用
比如求和api调用http://127.0.0.1:8000/test/?a=3&b=5
其中a和b是我们人为可输入的值返回a+b。a和b必须是两个整数,返回a+b的值
在这里插入图片描述
调用word2vec即http://127.0.0.1:8000/test/?a=hello传入一个字符串返回一个词向量。
在这里插入图片描述
下一步目标,调用这些api接口不要在本地调用,在自己的服务器上调用

猜你喜欢

转载自blog.csdn.net/qq_41569591/article/details/109456782
今日推荐