【问题标题】:Calling api without knowing ip address in django在 django 中不知道 IP 地址的情况下调用 api
【发布时间】:2018-02-17 17:36:40
【问题描述】:

我有一个帖子请求

http://localhost:8000/api/orders/shipment

我想要做的是我不想传递域/IP 地址并访问 API,例如 Django 管理控制台给出“172.18.0.1 - - [08/Sep/2017 14:30:29]”POST /adminorder/order/import/ HTTP/1.1“200”

我在 django 文档中搜索了 get_absolute_url() 方法来定义自定义 url,我不知道如何在这种情况下使用它。

【问题讨论】:

标签: django django-models django-templates django-rest-framework django-modeladmin


【解决方案1】:

我相信在请求中使用相对 url 是不可能的,但您可以通过创建一个将相关域添加到您的 url 的函数来解决这个问题。 (确保导入您的设置文件!)

from django.conf import settings

development_url = "http://localhost:8000/"
production_url = "http://myapisite.com/"

def create_url(relative_url):
    # If you are on your development server. This is assuming your development always has DEBUG = True, and your production is always DEBUG = False
    if settings.DEBUG:
        return development_url + relative_url

    # Production
    return production_url + relative_url

因此print(create_url("api/test/anothertest")) 将返回http://localhost:8000/api/test/anothertest

这就是你将如何使用它:

url = create_url("api/orders/shipment/")
data = requests.post(url=url, data=content, headers = headers)

【讨论】:

    猜你喜欢
    • 2013-12-09
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2020-09-29
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多