python - Heroku Django 邮件未发送
问题描述
我想用 Django-RestFramework 和 ReactjS 发送邮件。在本地机器上,发送邮件可以正常工作,但是如果我在 Heroku 上部署代码,我总是会收到类似的错误
NameError 类型的对象不是 JSON 可序列化 或SmtpAuthentication 错误对象不是可序列化的
有人能帮助我吗?
序列化器.py
class contactSerializer(serializers.Serializer):
name = serializers.CharField()
email = serializers.CharField()
subject = serializers.CharField()
message = serializers.CharField()
def validate(self, data):
print("data**********", data)
return data
def save(self):
email = self.validated_data['email']
message = self.validated_data['message']
subject = self.validated_data['subject']
name = self.validated_data['name']
cntct= contacts(name=name, email=email,subject=subject, message=message)
send_mail(subject, 'Name :'+name+'\n\n'+email+'\n\n\n\n' +
message, email,[email])
return cntct.save()
视图.py
class contactCreateandMailSend(generics.GenericAPIView):
permission_classes = (permissions.AllowAny,)
serializer_class = contactSerializer
def post(self, request, format=None):
serializer = contactSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
try:
serializer.save()
return Response({'sucesss': 'Message has been sent'})
except Exception as err:
return Response({'errors': err})
设置.py
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
import dj_database_url
db_from_env= dj_database_url.config(conn_max_age=600, ssl_require=True)
DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CORS_ORIGIN_ALLOW_ALL = True
CSRF_COOKIE_HTTPONLY = True
STATICFILES_DIRS = [
os.path.join(BASE_DIR, os.path.join(BASE_DIR, 'build/static')),
os.path.join(BASE_DIR, os.path.join(BASE_DIR, 'build')),
os.path.join(BASE_DIR, 'media'),
]
WHITENOISE_MIMETYPES = {
'.xsl': 'application/xml'
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 3
}
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
# If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
EMAIL_HOST_USER = os.environ.get('DB_USER')
EMAIL_HOST_PASSWORD = os.environ.get('DB_PASS')
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG=os.environ.get("DEBUG_VAL")
django_heroku.settings(locals())
响应体
TypeError at /contacts/mail/
Object of type SMTPAuthenticationError is not JSON serializable
Request Method: POST
Request URL: https://estate-real-appp.herokuapp.com/contacts/mail/
Django Version: 3.1.4
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.7.4
Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages']
Server time: Fri, 11 Dec 2020 03:25:22 +0000
Installed Applications:
['Account',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'drf_yasg',
'immobilien',
'listinghouse',
'contacts',
'corsheaders']
Installed 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',
'corsheaders.middleware.CorsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware']
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/response.py", line 70, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/renderers.py", line 103, in render
allow_nan=not self.strict, separators=separators
File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/utils/json.py", line 25, in dumps
return json.dumps(*args, **kwargs)
File "/app/.heroku/python/lib/python3.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/utils/encoders.py", line 67, in default
return super().default(obj)
File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
Exception Type: TypeError at /contacts/mail/
Exception Value: Object of type SMTPAuthenticationError is not JSON serializable
Request information:
USER: AnonymousUser
GET: No GET data
POST: No POST data
FILES: No FILES data
解决方案
推荐阅读
- sql-server - 如何通过 group by 得出每个 poly 的总支出?
- c - 如何使用 qsort 对结构的数组进行排序?
- docker - 错误解组内容:无效字符 '<' 寻找值的开头
- javascript - 来自字符串值的 Javascript 参数
- powerbi - 基于另一列值的条件计算
- java - 根据实现它们的类动态显示枚举值
- python-3.x - 应用程序的一个实例崩溃:APP/PROC/WEB: Exited with status 127
- c - #else 预处理器指令后的注释
- html - How to enlarge image without overlapping other elements?
- python - 获取列表字典的所有值