【问题标题】:Python: Return pre stored json file in response in Django Rest FrameworkPython:在 Django Rest Framework 中返回预存储的 json 文件作为响应
【发布时间】:2023-02-24 20:12:05
【问题描述】:

我想编写一个 API,它在 GET 调用时返回预存储的简单 json 文件。该文件应预先存储在文件系统中。怎么做?

注册是应用名称。 static 是寄存器内的文件夹。我在那里保留 stations.json 文件。注册/静态/stations.json。

此“stations.json”文件的内容应作为响应返回。

设置.py:

STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'register/static/')
]
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

意见.py:

from django.shortcuts import render

# Create your views here.
from django.contrib.auth.models import User
from .serializers import RegisterSerializer
from rest_framework import generics
from django.http import JsonResponse
from django.conf import settings
import json



class RegisterView(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = RegisterSerializer
    
    
def get_stations(request):
    with open(settings.STATICFILES_DIRS[0] + '/stations.json', 'r') as f:
        data = json.load(f)
    return JsonResponse(data)

网址.py:

from django.urls import path
from register.views import RegisterView
from . import views



urlpatterns = [
    path('register/', RegisterView.as_view(), name='auth_register'),
    path('stations/', views.get_stations, name='get_stations'),
]

设置/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('api/', include('register.urls')),
]

当我点击邮递员的 GET 请求时:“http://127.0.0.1:8000/api/stations/”,

我收到错误:500 内部服务器错误。

/api/stations/ 处的类型错误

错误:

<html lang="en">

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="robots" content="NONE,NOARCHIVE">
    <title>TypeError
        at /api/stations/</title>
    <style type="text/css">
        html * {
            padding: 0;
            margin: 0;
        }

【问题讨论】:

  • 你能发布完整的回溯吗
  • 您是否尝试使用这样的硬编码路径打开文件:with open('register/static/stations.json', 'r') as f:
  • @AbdulNiyasPM:这是一个大的 HTML 文件。

标签: python django


【解决方案1】:

您需要在 return JsonResponse(data) 中传递 safe=False 作为 return JsonResponse(data, safe=False)

【讨论】:

    猜你喜欢
    • 2013-04-09
    • 1970-01-01
    • 2018-03-24
    • 2014-12-07
    • 1970-01-01
    • 2019-08-19
    • 2019-11-09
    • 2014-12-17
    相关资源
    最近更新 更多