Gaurav Sharma
Gaurav Sharma

Reputation: 2770

Google App Engine Flask Project with PyCharm - sys.path.insert, virtualenv, site-packages

I have a Hello World project with the following code:

import sys
import os
sys.path.insert(1, os.path.join(os.path.abspath('.'), 'venv/lib/python2.7/site-packages'))

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

The first 3 lines are necessary, otherwise I get this error message in console

from flask import Flask
ImportError: No module named flask

Those first 3 lines, especially the sys.path.insert, are a bit ugly - is there another way I can set up the system paths with site-packages without having to declare it this way in code?

I'm using a virtualenv in case that makes any difference.

Upvotes: 2

Views: 255

Answers (2)

pgiecek
pgiecek

Reputation: 8200

You should use the vendoring mechanism to set up third party libraries for App Engine app. No need to modify sys.path in your files. Create lib directory directly in your application root and tell your app how to find libraries in this directory by means of appengine_config.py file.

from google.appengine.ext import vendor

# Add any libraries installed in the "lib" folder.
vendor.add('lib')

Use pip with the -t lib flag to install libraries in this directory.

$ pip install -t lib [lib-name]

Or

$ pip install -t lib -r requirements.txt

Check out this answer.

Upvotes: 2

Houman
Houman

Reputation: 66320

Remove sys.path.insert

PyCharm --> Preferences --> Project Interpreter --> Click on Gear Icon --> Add Local --> <browse to your virtualenv>/bin/python --> OK

Now when you run your project by right clicking your flaskapp.py --> Run make sure the virtualenv is attached to it, by clicking on the down arrow --> edit configuration --> check Python interpreter that the virtualenv you had specified before is actually used by PyCharm.

enter image description here enter image description here

Upvotes: 1

Related Questions