Skip to main content
 首页 » 编程设计

python之在终端中使用 Curl 和 Django Rest Framework

2024年08月22日34zdz8207

我有一个模型

class Item(models.Model): 
    user = models.ForeignKey(User, on_delete=models.CASCADE) 
    otheritemmodel = models.ForeignKey(Model, on_delete=models.CASCADE) 
    uuid = models.CharField(max_length=256, unique=True) 
    floatitem = models.FloatField() 
    relateditem = models.ForeignKey(RelatedItem, on_delete=models.CASCADE) 
    category = models.ForeignKey(Category, on_delete=models.CASCADE) 
    subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) 
    character = models.CharField(max_length=500, null=True, blank=True) 
    zipcode = models.IntegerField() 
    city = models.CharField(max_length=100) 
    state = models.CharField(max_length=100) 
    active = models.BooleanField(default=True) 
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) 

创建API View

class Item_Create_APIView(CreateAPIView): 
    authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication] 
    permission_classes = [IsAuthenticated] 
    serializer_class = ItemCreateSerializer 
    queryset = Item.objects.all() 

和序列化器

Create Serializer

我正在尝试通过终端中的 curl 或 http 测试 createView 帖子,但到目前为止还没有成功。我正在使用 python3.5 和 Django==1.8.10 以及带有 JWT token 身份验证的 Django Rest Framework。我可以登录并获取 token ,但我不知道如何将 json 数据格式化为 baseusrl/create_item 端点以通过 curl 测试 Create Post 调用以查看 API 是否有效。

有人对此有指导吗?谢谢

我试过了,没用:

curl —X POST H ”Authorization: JWT token” http://localhost:8000/create_item/ ‘{“key”:”val”}’  

我已经尝试过这种格式,但在调用 url 时出现“未指定 url”

curl -X POST -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE0NzEwMjc4MjIsImVtYWlsIjoicGF0b3JlQHByb3Rvbm1haWwuY2giLCJ1c2VybmFtZSI6InBhdG9yZUBwcm90b25tYWlsLmNoIn0.seO6ayMayJ8hwGf3Tlqwu95cZOw5VyFGVqsT5LymdJw" -H "Content-Type: application/json" -d “user=37&otheritmemodel=3&uuid=4454353454983543434&floatitem=40.0&relateditem=28&category=1&subcategory=1&character=jim&zipcode=11111&city=City&state=State” http://localhost:8000/user-api/create_item/ 

有什么想法吗?

请您参考如下方法:

经过深思熟虑,我喝了双倍的咖啡,并找到了使用 JWT 身份验证实现 POST 调用的正确方法。有一点需要注意,我必须在 protected URL 周围加上单引号,才能成功将记录保存到数据库中。我还选择不将 JSON 格式的数据作为键值对传递,因为 JSON 渲染器会处理它。

对于遇到相同问题的任何其他人,有效的语法是:

curl -H "Authorization: JWT YourToken" -d "field=value&field=value" 'http://127.0.0.1:8000/protected_url'