Showing posts with label flask. Show all posts
Showing posts with label flask. Show all posts

Monday, March 10, 2014

Upstart can't read environment variables

I was trying to configure a gunicorn server with upstart for easily starting/stopping my service. But it turned out to be problematic since upstart does not read environment variables.

How did I encounter this error? I was trying to parse signed_request from Facebook canvas via the following line:

fb_request = facebook.parse_signed_request(signed_request, APP_SECRET)

where

APP_SECRET = os.environ.get('FB_APP_SECRET', 'jhdklu3sh4o8y4o8fh34')

I realized that it couldn't read the environment variable and was using the default app secret so couldn't decrypt the signed request. My environment variables were in .bashrc of both regular user and root but it did not read. So I added them to the upstart script:

script
     export HOME=/home/user/project
     cd $HOME
     export FB_APP_ID=859827u4fhk4vnf
     export FB_APP_SECRET=4ojfo92ufo2489fyuo482fy2
     . venv/bin/activate
     exec gunicorn myapp:app
end script


Saturday, February 1, 2014

Flask, Facebook Canvas App, localhost and SSL


If you're developing a facebook canvas app with Flask, then you're asked to provide URLs for your app. Initially I used myapp.herokuapp.com address for http and https. But I realized that for testing local changes, I'd like to use localhost.

When I give localhost, it says it's not SSL supported. Then I had to create SSL certificates and install pyopenssl to use them. See: http://kracekumar.com/post/54437887454/ssl-for-flask-local-development

But what I saw was that connection was untrusted and I could not Add an Exception. I learned that browsers do not trust localhost for SSL. So I had to create an alias for my herokuapp. Added the following line to /etc/hosts

127.0.0.1 myapp.herokuapp.com

And set the canvas url as myapp.herokuapp.com for http and https.

Now when the app starts, tries to load https://myapp.herokuapp.com. It loads https://127.0.0.1:443 which is listened by the Flask app:

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 443))
    app.run('0.0.0.0', debug=True, port=port, ssl_context=('/home/user/projects/myapp/server.crt', '/home/user/projects/myapp/server.key'))

This way I could overcome the SSL localhost problem for facebook canvas apps.

UPDATE: If you don't want to run the app as root,  just forward port 443 to 3000 and listen 3000 port with the following command as root:

iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to-port 3000

and to cancel it:

iptables -t nat -D OUTPUT -p tcp --dport 443 -j REDIRECT --to-port 3000

Note that forwarding 443, you won't be able to connect SSL web sites throughout your pc.

Maybe using vagrant could be more elegant.