How can I get Django on Google App Engine to automatically email server 500 errors to Admins? - django

When my App raises a server 500 error, I'm not receiving the automatic Django email that it should be sending: https://docs.djangoproject.com/en/1.3/howto/error-reporting/
I'm using the Google App Engine Django Helper at http://code.google.com/p/google-app-engine-django/
In my settings.py file:
DEBUG = False
ADMINS = (('Support', 'Support#******.com'),)
EMAIL_HOST = ''
SERVER_EMAIL = 'Support#******.com'
In the Google App Engine Dashboard, I've added Support#**.com (The same email in my settings.py) to the admins with the role of Viewer. I've tried changing the role to Developer.
I think the problem is this line:
EMAIL_HOST = ''
Since the Django docs say
In order to send e-mail, Django
requires a few settings telling it how
to connect to your mail server. At the
very least, you’ll need to specify
EMAIL_HOST. . .
But, the there are comments in the settings.py file that came with the google-app-engine-django project that say
# Ensure that email is not sent via SMTP by default to match the standard App
# Engine SDK behaviour. If you want to send email via SMTP then add the name of
# your mailserver here.
EMAIL_HOST = ''

Make sure you specify the 'SERVER_EMAIL' (https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-SERVER_EMAIL) in your settings. Otherwise the emails will be sent from "root#localhost" and AppEngine won't send them.

Related

How to send emails from django shell with AWS ses?

I have verified my domain with AWS SES and as a result my site successfully does send password verification emails (via allauth).
I would, however, also like to be able to send emails based on local scripts. To do this I have been using django shell_plus:
from django.core.mail import send_mail
send_mail("It works!", "This will get sent through anymail",
"me#mysite.com", ["me#mysite.com"])
I get output of '1' suggesting this the email has been sent successfully but I do not receive an email
I think my config is correct given that the site does successfully send emails:
EMAIL_BACKEND = "anymail.backends.amazon_ses.EmailBackend"
ANYMAIL = {
"AMAZON_SES_CLIENT_PARAMS": {
"aws_access_key_id": AWS_ACCESS_KEY_ID,
"aws_secret_access_key": AWS_SECRET_ACCESS_KEY,
"region_name": "us-east-1",
},
}
Can anyone explain what I need to do to send emails from the terminal i.e. without being directly logged into an AWS server?
Was a basic error - I had the required settings in my production config file, but not in my dev config file

flask sessions not persistent between requests from cross domains

I have a frontend vue site hosted on google's firebase with the url (https://front-end.web.com) , while my flask backend is hosted on heroku with the url (https://back-end.heroku.com). This makes my session not to persist across requests, I tried fixing this by implementing CORS on my backend, but for some reason it's not working , below are snippets of my code to show my implementation
config_class.py
class ConfigClass():
CORS_ALLOW_HEADERS = ['Content-Type']
CORS_ORIGINS = ['https://front-end.web.com']
SECRET_KEY = os.environ.get("APP_SECRET_KEY")
SESSION_TYPE = 'redis'
_init.py
from flask import Flask, session
from flask_session import Session
from flask_cors import CORS
from root_folder.config import ConfigClass
db = SQLAlchemy()
migrate = Migrate()
ma = Marshmallow()
sess = Session()
def create_app(ConfigClass):
# initiate the flask app and assign the configurations #
app = Flask(__name__)
app.config.from_object(config_options[config_class])
sess.init_app(app)
from root_folder.clients import clients_app
# register all the blueprints in this application
app.register_blueprint(clients_app)
CORS(app, supports_credentials=True)
# return the app object to be executed
return app
app.py
from root_folder import create_app
app = create_app()
Procfile:
web: gunicorn -w 1 app:app
axios front end request
let formData = new FormData();
formData.append("email", email);
formData.append("password", password);
axios.post(
backendUrl+'create_client_account',
formData,
{
withCredentials: true,
headers:{
"Content-Type": "multipart/form-data"
}
}
);
create client route ( I have stripped this code block to the bare minimum to make it understandable):
from flask import session
# route for creating account credentials
#bp_auth_clients_app.route("/create_client", methods=["POST"])
def create_client():
username = request.form.get("username").lower()
email = request.form.get("email").lower()
# create account code goes here #
auth_authentication = True
session["auth_authentication"] = auth_authentication
req_feedback = {
"status": True,
"message": "Account was successfully created",
"data": feedback_data
}
return jsonify(req_feedback), 200
After the account is successfully created, I am unable to access the session value in subsequent requests, it returns None.
To recreate the problem on my local server, I access the front-end via the domain "localhost:8080" , while I access the flask server via "127.0.0.1:8000" . If I change the front end domain to "127.0.0.1:8080", I don't usually have any problems.
Kindly advice on what to do.
Thanks to Ahmad's suggestion, I was able to resolve the issue using custom domains for both my frontend and backend as follows:
frontend.herokuapp.com -> customDomain.com
backend.herokuapp.com -> api.customDOmain.com
finally I added the line below to my session config:
SESSION_COOKIE_DOMAIN = ".customDomain.com"
And all was well and good.
Sessions use cookies:
On session creation the server will send the cookie value in the set-cookie header. It doesn't work for you because of cross origin issue.
It works fine for you when you use 127.0.0.1 because 127.0.0.1:8080 and 127.0.0.1:8000 are the same origin so the browser accepts the set-cookie header and do set the cookie no problem.
Cookies are sent in the header on each request and your server loads the session from Redis by cookie value (The cookie value is called session_id).
How it gets inserted => Normally your session gets serialized and inserted in Redis with the cookie hash as Key in the end of the request life cycle.
If you want to keep using sessions and cookies you need to find another solution for your deployment to so that your backend and frontend have the same hostname.
If you can't do I'd recommend to read about JWT (Json-Web-Tokens).
EDIT
You can send the session id in your response body and save it in local storage.
Then you need to configure:
frontend set the session id value it in the Authorization header base64 encoded.
Backend base64 decode Authorization header value from request and check for the session in Redis, if exists load it.
EDIT
How to deploy both backend/frontend on same hostname using apache:
using apache you need to create 2 virtual hosts one for backend and the other for frontend listening on different ports then configure your web server deployment to use the backend VH if the path is prefixed by /api/ and use the frontend Virtual host for anything else.
This way any request you make to your api your backend will handle it otherwise it'll serve your frontend app.
This is just a way on how to do it there is plenty others
Check this question.

Sending SMTP email with Django and Sendgrid on Heroku

I'm trying to send email using SMTP and sendgrid for a Django app. I'm able to send emails on my local server, but on my heroku app I get an "SMTPServerDisconnected" error saying "connection unexpectedly closed. Is there a way to send SMTP email with sendgrid once deployed to Heroku? I can't seem to find any documentation on this.
Here are my settings for email in settings.py:
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'EMAIL_HOST_USER'
EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'email#email.com'
SENDGRID_API_KEY='SENDGRID_API_KEY'
SENDGRID_PASSWORD='SENDGRID_PASSWORD'
SENDGRID_USERNAME='SENDGRID_USERNAME'
Please let me know what settings you use to send SMTP email. Thanks.
You need to go into your Sendgrid dyno. Navigate to Settings>API Keys.
Click on create API Key, at the time of writing this it is a blue button in the top right corner of the page.
copy the key that they generate for you and paste it somewhere on your local machine, also navigate back to your heroku page. Navigate to your app's Settings and click on "reveal config variables". You should now see key value pairs of all the environment variables. In the Key column add "SENDGRID_API_KEY" and in the value column add the key that you copied from the Sendgrid website. At this point the following python code should work:
sg = sendgrid.SendGridAPIClient(os.environ['SENDGRID_API_KEY'])
message = Mail(from_email='example#example.com', to_emails='example#example.com',
subject='Example Subject ', html_content='<strong>and easy to do anywhere, even with Python</strong>')
response = sg.send(message)
If you keep the response variable you can wrap the code in a try except block can try to catch errors. Sorry for the formatting I am still new to posting on stack overflow.

How to make game use https when played via facebook and http when played from other domain

Our users play our Django game directly via our domain, cnamed to herokuapp.com. We request our assets via http.
We want to add our game to facebook, which requires using https. Heroku can handle this.
Using https requests: our game works on facebook but fails to load assets when accessed via our cnamed domain.
Can we make our game use https when played via facebook and http when played from our domain? What code must we add to settings.py?
We've tried this code in settings.py but it didn't work
Option 1:
import socket
if socket.gethostname().startswith('app'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
Option 2:
import socket
if socket.gethostname().startswith('edge'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
You could use protocol relative urls to save yourself from the pain of worrying about the protocol to use.
So the settings would look like:
STATIC_URL = "//d******1.cloudfront.net/"
and you can safely get rid of all the computation logic in your code snippet.

django socialauth twitter , google oauth , facebook does not work

This is my first post, and I have a problem I could not make it work django OMAB socialauth of three things I just need to google, facebook, and twitter, google works well with open id, but not much twitter and I put in my
settings. py:
TWITTER_CONSUMER_KEY = '00' this is no real
TWITTER_CONSUMER_SECRET = '00' this is no real
FACEBOOK_APP_ID = '' ihave no key
FACEBOOK_API_SECRET = ''
LINKEDIN_CONSUMER_KEY = ''
LINKEDIN_CONSUMER_SECRET = ''
ORKUT_CONSUMER_KEY = ''
ORKUT_CONSUMER_SECRET = ''ihave no key
GOOGLE_OAUTH2_CLIENT_ID = ''
GOOGLE_OAUTH2_CLIENT_SECRET = ''
SOCIAL_AUTH_CREATE_USERS = True
SOCIAL_AUTH_FORCE_RANDOM_USERNAME = False
SOCIAL_AUTH_DEFAULT_USERNAME = 'socialauth_user'
SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
LOGIN_ERROR_URL = '/login/error/'
#SOCIAL_AUTH_USER_MODEL = 'app.CustomUser'
SOCIAL_AUTH_ERROR_KEY = 'socialauth_error'
GITHUB_APP_ID = ''
GITHUB_API_SECRET = ''
FOURSQUARE_CONSUMER_KEY = ''
FOURSQUARE_CONSUMER_SECRET = ''
LOGIN_URL = '/login-form/'
LOGIN_REDIRECT_URL = '/'
LOGIN_ERROR_URL = '/login-error/'
I am using the example that comes in the zip of OMAB socialauth django , but not working.
When I created my twitter app, I wrote my domain www.sisvei.com , I am testing locally socialauth django ie 127.0.0.1:8000, then sign in with twitter sends me to this url:
http://127.0.0.1:8000/login/error/ and a message saying is the Incorrect authentication service
this happens with facebook and google oauth and oauth2
I'm new to django and I this much work comprising this part of django socialath hopefully help me, thank you very much.
You need to be more specific on "why it doesn't work". Where are you getting the errors?
When debugging a third-party oauth/openid app in Django, generally it boils down to:
configuration & keys - did you make sure to obtain all of the necessary API keys for the services you will be using, and to add them to your configuration?
urls - did you remember to add the necessary urlpatterns to your base urls.py file?
authentication setup on the server - often, you'll need to have a file available or respond with a specific header when the authentication service hits your server. Have you checked to make sure that is set up?
databases - have you run syncdb after installing the app? Are all the tables set up?
templates - if the third party app requires you to set up templates, do you have them set up?
custom views - are you using custom views? If so, try using the built-in views that came with the third party app first, to see if they work
After those are confirmed, you're going to want to be able to see what requests are taking place. Use the debugger included in Chrome/Safari, or get the web developer add-on for Firefox, and look at the network requests as they happen. Do you see HTTP responses other than 200 (say, 404, 500, 403, etc?) those mean that the services aren't responding correctly.
From your error, it looks like you have not correctly set up your callback URL on Twitter. It should be sending you to www.sisvei.com, not 127.0.0.1. Alternatively, check the URL when you get to the Twitter login page -- is the callback URL in the URL, and is it pointing to 127.0.0.1? Then Django is sending it the wrong callback URL.
Finally this:
I wrote my domain www.sisvei.com python does not support this
Is unclear. As far as I know, Python doesn't care what the domain is.
WAIT A MINUTE ...
Are you using runserver? Are you getting the following error?
Error: "www.sisvei.com" is not a valid port number or address:port pair.
If so, there is an easy fix! Just run it like so:
python manage.py runserver www.sisvei.com:80
That should resolve your error if that's what's happening. You're probably running it as
python manage.py runserver 127.0.0.1
127.0.0.1 is a reserved IP address that points back to localhost, your own computer. As a result, it is not possible to use it for authentication or any other purpose outside of programs running on your own machine. See this article for more info.
I'm not sure, but I might be having similar problems, oscar. For me, SocialAuth was generating an AuthenticationURL for facebook, foursquare and hotmail, but not for google, twitter or any of the other address it supports. I think it may be something wrong with the API, so I posted an issue on the social-auth google group...you may want to check there to see if anyone updates!!
https://code.google.com/p/socialauth/issues/detail?id=282&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Modified