如何从不同的机器上的本地网络访问Django Rest Framework(DRF)API?

huangapple go评论82阅读模式
英文:

How to access drf(django rest framework) api in local network from different machine?

问题

我在Apache服务器上部署了一个DRF API,当我从同一台机器访问它时,它正常工作(GET和POST请求以及数据库连接都正常),但当我尝试从同一网络中的另一台机器访问时,我遇到了两个错误,特别是如果是一个POST请求或与数据库有连接的情况下,第一个错误在发送任何内容之前说:

> "HTTP 405 Method Not Allowed"

如果我尝试发送POST请求,它会说:

> "CSRF Failed: CSRF token missing or incorrect."

如果有一个GET请求与数据库有连接,我会得到500服务器错误。我尝试按照文档进行操作,并查找了这些问题12,但没有帮助,实际上我甚至不确定是什么导致了这些问题。
注意:当我尝试运行runserver命令时,从其他计算机上也可以正常工作。
以下是虚拟主机和settings.py的配置。
虚拟主机:

<VirtualHost 192.168.100.102:8001 _default_:8001>
    
    DocumentRoot /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
    ServerAdmin yaz@gmail.com
     
    # Set the path to your Django project
    WSGIDaemonProcess myproject python-home=/opt/bitnami/projects/chatbotQZ/sources/env/ python-path=/opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
    WSGIProcessGroup myproject
    WSGIScriptAlias / /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject/wsgi.py

    # Configure access to static files
    Alias /static/ /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static
    <Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static>
        Require all granted
    </Directory>

    <Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject>
        Require all granted
    </Directory>

    ErrorLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_error.log
    CustomLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_access.log combined
</VirtualHost>

settings.py:

"""
Django settings for myproject project.

Generated by 'django-admin startproject' using Django 3.2.18.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=z(3%l&3lrwvz16411c!-kjqaeb#@644o4$cd&go!w0ymi6(30'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

#ALLOWED_HOSTS = ['127.0.0.1']
ALLOWED_HOSTS = ['192.168.100.102']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'base',
]
AUTH_USER_MODEL = 'base.user_auth'
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'chatbot',
        'USER': 'dev',
        'PASSWORD': 'wXNjZWoJmBB5',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
英文:

I deployed a drf api in apache server , when i access it from the same machine it work fine (get and post requests and also database connections all works good) , but when I try it from another machine in the same network i got two errors specially if it's a post request or there is a connection with database , the first one before sending anything it said

> "HTTP 405 Method Not Allowed"

and if I try to send post requests it said

> "CSRF Failed: CSRF token missing or incorrect."

and also if there is a get request has connections to database i got 500 server error .
I tried to follow the documentation and also looked for these questions 1 , 2 but didn't help , actually I'm not even sure what cause these problems .
Note : when i try just runserver command it works fine from other machines .
here is virtual host and settings.py .
virtual host:

&lt;VirtualHost 192.168.100.102:8001 _default_:8001&gt;
DocumentRoot /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
ServerAdmin yaz@gmail.com
# Set the path to your Django project
WSGIDaemonProcess myproject python-home=/opt/bitnami/projects/chatbotQZ/sources/env/ python-path=/opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
WSGIProcessGroup myproject
WSGIScriptAlias / /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject/wsgi.py
# Configure access to static files
Alias /static/ /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static
&lt;Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static&gt;
Require all granted
&lt;/Directory&gt;
&lt;Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject&gt;
Require all granted
&lt;/Directory&gt;
ErrorLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_error.log
CustomLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_access.log combined
&lt;/VirtualHost&gt;

settings.py :

&quot;&quot;&quot;
Django settings for myproject project.
Generated by &#39;django-admin startproject&#39; using Django 3.2.18.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
&quot;&quot;&quot;
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / &#39;subdir&#39;.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = &#39;django-insecure-=z(3%l&amp;3lrwvz16411c!-kjqaeb#@644o4$cd&amp;go!w0ymi6(30&#39;
# SECURITY WARNING: don&#39;t run with debug turned on in production!
DEBUG = False
#ALLOWED_HOSTS = [&#39;127.0.0.1&#39;]
ALLOWED_HOSTS = [&#39;192.168.100.102&#39;]
# Application definition
INSTALLED_APPS = [
&#39;django.contrib.admin&#39;,
&#39;django.contrib.auth&#39;,
&#39;django.contrib.contenttypes&#39;,
&#39;django.contrib.sessions&#39;,
&#39;django.contrib.messages&#39;,
&#39;django.contrib.staticfiles&#39;,
&#39;rest_framework&#39;,
&#39;base&#39;,
]
AUTH_USER_MODEL = &#39;base.user_auth&#39;
MIDDLEWARE = [
&#39;django.middleware.security.SecurityMiddleware&#39;,
&#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,
&#39;django.middleware.common.CommonMiddleware&#39;,
&#39;django.middleware.csrf.CsrfViewMiddleware&#39;,
&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,
&#39;django.contrib.messages.middleware.MessageMiddleware&#39;,
&#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,
]
ROOT_URLCONF = &#39;myproject.urls&#39;
TEMPLATES = [
{
&#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,
&#39;DIRS&#39;: [],
&#39;APP_DIRS&#39;: True,
&#39;OPTIONS&#39;: {
&#39;context_processors&#39;: [
&#39;django.template.context_processors.debug&#39;,
&#39;django.template.context_processors.request&#39;,
&#39;django.contrib.auth.context_processors.auth&#39;,
&#39;django.contrib.messages.context_processors.messages&#39;,
],
},
},
]
WSGI_APPLICATION = &#39;myproject.wsgi.application&#39;
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
&#39;default&#39;: {
&#39;ENGINE&#39;: &#39;django.db.backends.mysql&#39;,
&#39;NAME&#39;: &#39;chatbot&#39;,
&#39;USER&#39;: &#39;dev&#39;,
&#39;PASSWORD&#39;: &#39;wXNjZWoJmBB5&#39;,
&#39;HOST&#39;: &#39;127.0.0.1&#39;,
&#39;PORT&#39;: &#39;3306&#39;,
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.UserAttributeSimilarityValidator&#39;,
},
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.MinimumLengthValidator&#39;,
},
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.CommonPasswordValidator&#39;,
},
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.NumericPasswordValidator&#39;,
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = &#39;en-us&#39;
TIME_ZONE = &#39;UTC&#39;
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = &#39;/static/&#39;
STATIC_ROOT = os.path.join(BASE_DIR, &quot;static/&quot;)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = &#39;django.db.models.BigAutoField&#39;

答案1

得分: 0

有几个可能导致您出现此问题的原因。我将介绍其中一些。

  1. 确保IP地址 &#39;192.168.100.102&#39; 是当前托管您的应用程序的机器的IP地址。
  2. 确保托管您的应用程序的机器能够与托管数据库的机器进行通信。如果它们在同一台机器上,那么它们可能不应该出现任何问题。
  3. 确保您的应用程序的CORS策略已正确设置,以接受来自其他来源的请求。
英文:

There are a couple of reasons you might be experiencing this. I’ll go over a few of those.

  1. Be sure the ip &#39;192.168.100.102&#39; is the ip of the machine currently hosting your application.
  2. Make sure the machine your application is on can communicate with the machine your database is hosted on. If they are on the same machine then they probably shouldn’t be having any issues.
  3. Ensure that CORS policy for your application is properly set to accept requests from other origins.

答案2

得分: 0

主要问题是 CSRF 令牌,当我在 Postman 中禁用了 Cookies 并在标头中发送了 CSRF 令牌时,它起作用了,但即使我决定将其删除,通过从 rest-framework/settings.py 中删除 'rest_framework.authentication.SessionAuthentication',它也能正常工作。

英文:

the main problem was csrf token , when I used postman and disabled cookies and send csrf token in header it worked , but even tho I decide to remove it , by deleting 'rest_framework.authentication.SessionAuthentication' from rest-framework/settings.py and it's work fine .

huangapple
  • 本文由 发表于 2023年7月10日 23:07:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定