【问题标题】:How to connect the library for http requests?如何为 http 请求连接库?
【发布时间】:2019-01-25 05:17:53
【问题描述】:

我正在尝试连接库以处理查询。

一开始我尝试连接this

我的步骤:

  1. pip 安装请求
  2. 在views.py中:
    import requests
    ....
    def my_view(request):
        ...
        req = requests.get('https://api.github.com/events')`

我得到一个错误内部服务器错误

我也尝试使用 urllib.request

在views.py中:

    import urllib.request
    ....
    def my_view(request):
        ...
        req = urllib.request.Request('https://api.github.com/events')`

我又收到一个内部服务器错误

我做错了什么?

附言

views.py 文件:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
import requests
import json
import urllib.request

def check_auth(request):

    #req = requests.get('https://api.github.com/events')

    #req = urllib.request.Request('https://api.github.com/events')

    return render(request, 'authorization/lc.html')

【问题讨论】:

  • 请发布您的视图代码的其余部分您在控制台上看到的错误消息并带有回溯。
  • 在您的网络服务器错误日志中查看正在引发的实际错误。
  • @JohnGordon nginx 日志中没有错误
  • 如果您收到 500 错误,则一定是某处记录了错误。
  • 您的 Python 代码没有在 nginx 中运行,您必须使用 gunicornuwsgi 等类似的东西。检查这些日志。如果做不到这一点,请尝试使用开发服务器。还可以考虑在您的settings.py 中启用DEBUG

标签: python django python-3.x python-requests


【解决方案1】:

从我自己的 Django 站点运行代码,它似乎可以工作。所以这可能是你其他代码的问题。

一种检查方法是在控制台中单独尝试请求

import requests

req=requests.get('https://api.github.com/events')
print(req.status_code)

如果它在控制台中工作,它应该在 Django 视图中工作。

只是好奇,您为什么需要在自己的网站上请求另一个网站?

【讨论】:

  • 谢谢,问题已解决。我需要使用 api,为此需要提出请求
  • @mrmaaak 出了什么问题?
猜你喜欢
  • 2017-04-30
  • 2019-08-04
  • 1970-01-01
  • 2015-12-30
  • 2016-01-18
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多