英文:
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服务器错误。我尝试按照文档进行操作,并查找了这些问题1,2,但没有帮助,实际上我甚至不确定是什么导致了这些问题。
注意:当我尝试运行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:
<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'
答案1
得分: 0
有几个可能导致您出现此问题的原因。我将介绍其中一些。
- 确保IP地址
'192.168.100.102'
是当前托管您的应用程序的机器的IP地址。 - 确保托管您的应用程序的机器能够与托管数据库的机器进行通信。如果它们在同一台机器上,那么它们可能不应该出现任何问题。
- 确保您的应用程序的CORS策略已正确设置,以接受来自其他来源的请求。
英文:
There are a couple of reasons you might be experiencing this. I’ll go over a few of those.
- Be sure the ip
'192.168.100.102'
is the ip of the machine currently hosting your application. - 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.
- 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 .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论