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

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

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的配置。
虚拟主机:

  1. <VirtualHost 192.168.100.102:8001 _default_:8001>
  2. DocumentRoot /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
  3. ServerAdmin yaz@gmail.com
  4. # Set the path to your Django project
  5. WSGIDaemonProcess myproject python-home=/opt/bitnami/projects/chatbotQZ/sources/env/ python-path=/opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
  6. WSGIProcessGroup myproject
  7. WSGIScriptAlias / /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject/wsgi.py
  8. # Configure access to static files
  9. Alias /static/ /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static
  10. <Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static>
  11. Require all granted
  12. </Directory>
  13. <Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject>
  14. Require all granted
  15. </Directory>
  16. ErrorLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_error.log
  17. CustomLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_access.log combined
  18. </VirtualHost>

settings.py:

  1. """
  2. Django settings for myproject project.
  3. Generated by 'django-admin startproject' using Django 3.2.18.
  4. For more information on this file, see
  5. https://docs.djangoproject.com/en/3.2/topics/settings/
  6. For the full list of settings and their values, see
  7. https://docs.djangoproject.com/en/3.2/ref/settings/
  8. """
  9. import os
  10. from pathlib import Path
  11. # Build paths inside the project like this: BASE_DIR / 'subdir'.
  12. BASE_DIR = Path(__file__).resolve().parent.parent
  13. # Quick-start development settings - unsuitable for production
  14. # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
  15. # SECURITY WARNING: keep the secret key used in production secret!
  16. SECRET_KEY = 'django-insecure-=z(3%l&3lrwvz16411c!-kjqaeb#@644o4$cd&go!w0ymi6(30'
  17. # SECURITY WARNING: don't run with debug turned on in production!
  18. DEBUG = False
  19. #ALLOWED_HOSTS = ['127.0.0.1']
  20. ALLOWED_HOSTS = ['192.168.100.102']
  21. # Application definition
  22. INSTALLED_APPS = [
  23. 'django.contrib.admin',
  24. 'django.contrib.auth',
  25. 'django.contrib.contenttypes',
  26. 'django.contrib.sessions',
  27. 'django.contrib.messages',
  28. 'django.contrib.staticfiles',
  29. 'rest_framework',
  30. 'base',
  31. ]
  32. AUTH_USER_MODEL = 'base.user_auth'
  33. MIDDLEWARE = [
  34. 'django.middleware.security.SecurityMiddleware',
  35. 'django.contrib.sessions.middleware.SessionMiddleware',
  36. 'django.middleware.common.CommonMiddleware',
  37. 'django.middleware.csrf.CsrfViewMiddleware',
  38. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  39. 'django.contrib.messages.middleware.MessageMiddleware',
  40. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  41. ]
  42. ROOT_URLCONF = 'myproject.urls'
  43. TEMPLATES = [
  44. {
  45. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  46. 'DIRS': [],
  47. 'APP_DIRS': True,
  48. 'OPTIONS': {
  49. 'context_processors': [
  50. 'django.template.context_processors.debug',
  51. 'django.template.context_processors.request',
  52. 'django.contrib.auth.context_processors.auth',
  53. 'django.contrib.messages.context_processors.messages',
  54. ],
  55. },
  56. },
  57. ]
  58. WSGI_APPLICATION = 'myproject.wsgi.application'
  59. # Database
  60. # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
  61. DATABASES = {
  62. 'default': {
  63. 'ENGINE': 'django.db.backends.mysql',
  64. 'NAME': 'chatbot',
  65. 'USER': 'dev',
  66. 'PASSWORD': 'wXNjZWoJmBB5',
  67. 'HOST': '127.0.0.1',
  68. 'PORT': '3306',
  69. }
  70. }
  71. # Password validation
  72. # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
  73. AUTH_PASSWORD_VALIDATORS = [
  74. {
  75. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  76. },
  77. {
  78. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  79. },
  80. {
  81. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  82. },
  83. {
  84. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  85. },
  86. ]
  87. # Internationalization
  88. # https://docs.djangoproject.com/en/3.2/topics/i18n/
  89. LANGUAGE_CODE = 'en-us'
  90. TIME_ZONE = 'UTC'
  91. USE_I18N = True
  92. USE_L10N = True
  93. USE_TZ = True
  94. # Static files (CSS, JavaScript, Images)
  95. # https://docs.djangoproject.com/en/3.2/howto/static-files/
  96. STATIC_URL = '/static/'
  97. STATIC_ROOT = os.path.join(BASE_DIR, "static/")
  98. # Default primary key field type
  99. # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
  100. 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:

  1. &lt;VirtualHost 192.168.100.102:8001 _default_:8001&gt;
  2. DocumentRoot /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
  3. ServerAdmin yaz@gmail.com
  4. # Set the path to your Django project
  5. WSGIDaemonProcess myproject python-home=/opt/bitnami/projects/chatbotQZ/sources/env/ python-path=/opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject
  6. WSGIProcessGroup myproject
  7. WSGIScriptAlias / /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject/wsgi.py
  8. # Configure access to static files
  9. Alias /static/ /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static
  10. &lt;Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static&gt;
  11. Require all granted
  12. &lt;/Directory&gt;
  13. &lt;Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject&gt;
  14. Require all granted
  15. &lt;/Directory&gt;
  16. ErrorLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_error.log
  17. CustomLog /opt/bitnami/projects/chatbotQZ/sources/logs/drfapp_access.log combined
  18. &lt;/VirtualHost&gt;

settings.py :

  1. &quot;&quot;&quot;
  2. Django settings for myproject project.
  3. Generated by &#39;django-admin startproject&#39; using Django 3.2.18.
  4. For more information on this file, see
  5. https://docs.djangoproject.com/en/3.2/topics/settings/
  6. For the full list of settings and their values, see
  7. https://docs.djangoproject.com/en/3.2/ref/settings/
  8. &quot;&quot;&quot;
  9. import os
  10. from pathlib import Path
  11. # Build paths inside the project like this: BASE_DIR / &#39;subdir&#39;.
  12. BASE_DIR = Path(__file__).resolve().parent.parent
  13. # Quick-start development settings - unsuitable for production
  14. # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
  15. # SECURITY WARNING: keep the secret key used in production secret!
  16. SECRET_KEY = &#39;django-insecure-=z(3%l&amp;3lrwvz16411c!-kjqaeb#@644o4$cd&amp;go!w0ymi6(30&#39;
  17. # SECURITY WARNING: don&#39;t run with debug turned on in production!
  18. DEBUG = False
  19. #ALLOWED_HOSTS = [&#39;127.0.0.1&#39;]
  20. ALLOWED_HOSTS = [&#39;192.168.100.102&#39;]
  21. # Application definition
  22. INSTALLED_APPS = [
  23. &#39;django.contrib.admin&#39;,
  24. &#39;django.contrib.auth&#39;,
  25. &#39;django.contrib.contenttypes&#39;,
  26. &#39;django.contrib.sessions&#39;,
  27. &#39;django.contrib.messages&#39;,
  28. &#39;django.contrib.staticfiles&#39;,
  29. &#39;rest_framework&#39;,
  30. &#39;base&#39;,
  31. ]
  32. AUTH_USER_MODEL = &#39;base.user_auth&#39;
  33. MIDDLEWARE = [
  34. &#39;django.middleware.security.SecurityMiddleware&#39;,
  35. &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,
  36. &#39;django.middleware.common.CommonMiddleware&#39;,
  37. &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,
  38. &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,
  39. &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,
  40. &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,
  41. ]
  42. ROOT_URLCONF = &#39;myproject.urls&#39;
  43. TEMPLATES = [
  44. {
  45. &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,
  46. &#39;DIRS&#39;: [],
  47. &#39;APP_DIRS&#39;: True,
  48. &#39;OPTIONS&#39;: {
  49. &#39;context_processors&#39;: [
  50. &#39;django.template.context_processors.debug&#39;,
  51. &#39;django.template.context_processors.request&#39;,
  52. &#39;django.contrib.auth.context_processors.auth&#39;,
  53. &#39;django.contrib.messages.context_processors.messages&#39;,
  54. ],
  55. },
  56. },
  57. ]
  58. WSGI_APPLICATION = &#39;myproject.wsgi.application&#39;
  59. # Database
  60. # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
  61. DATABASES = {
  62. &#39;default&#39;: {
  63. &#39;ENGINE&#39;: &#39;django.db.backends.mysql&#39;,
  64. &#39;NAME&#39;: &#39;chatbot&#39;,
  65. &#39;USER&#39;: &#39;dev&#39;,
  66. &#39;PASSWORD&#39;: &#39;wXNjZWoJmBB5&#39;,
  67. &#39;HOST&#39;: &#39;127.0.0.1&#39;,
  68. &#39;PORT&#39;: &#39;3306&#39;,
  69. }
  70. }
  71. # Password validation
  72. # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
  73. AUTH_PASSWORD_VALIDATORS = [
  74. {
  75. &#39;NAME&#39;: &#39;django.contrib.auth.password_validation.UserAttributeSimilarityValidator&#39;,
  76. },
  77. {
  78. &#39;NAME&#39;: &#39;django.contrib.auth.password_validation.MinimumLengthValidator&#39;,
  79. },
  80. {
  81. &#39;NAME&#39;: &#39;django.contrib.auth.password_validation.CommonPasswordValidator&#39;,
  82. },
  83. {
  84. &#39;NAME&#39;: &#39;django.contrib.auth.password_validation.NumericPasswordValidator&#39;,
  85. },
  86. ]
  87. # Internationalization
  88. # https://docs.djangoproject.com/en/3.2/topics/i18n/
  89. LANGUAGE_CODE = &#39;en-us&#39;
  90. TIME_ZONE = &#39;UTC&#39;
  91. USE_I18N = True
  92. USE_L10N = True
  93. USE_TZ = True
  94. # Static files (CSS, JavaScript, Images)
  95. # https://docs.djangoproject.com/en/3.2/howto/static-files/
  96. STATIC_URL = &#39;/static/&#39;
  97. STATIC_ROOT = os.path.join(BASE_DIR, &quot;static/&quot;)
  98. # Default primary key field type
  99. # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
  100. 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:

确定