Forums

question for flask

I have flaks code as below:

@app.route('/newapi1', methods=['GET'])
def newapi1():

    url = request.args.get('url',default='',type=str)

    response = ""

    try:

        response = requests.get(url).text

    except Exception as e:

        response = str(e)

    finally:
        return response

Will this store temp file in my folder when it is run? If yes, which folder. It will direct the url to its contents.

in wsgi.py

# import flask app but need to call it "application" for WSGI to work

from flask_app import app as application

from flask_app_1 import app as application

Is this correct way to add multiple file to run at one time?

[edited by admin: formatting]

It won't store a temp file. Why do you think it would do so?

The way to to run multiple flask apps is to create multiple webapps from the PythonAnywhere dashboard, not adding multiple applications to the wsgi.py file.

Hi Conrad,

I have create all api in one file call flask_app currently. I just want to make it more manageable by separate to a few files.

Is it possible without create a new webapp?

Sure, but if you're just looking to organise your views into files you don't need to have multiple apps. You can simply define the views in one file, and then use them in the single app.

Hi Glenn,

what do you mean define the view? Can you give me an example?

have some files, called, eg, api_1.py and api_2.py that contain your @app.route view funcitons, as many as you need to keep them tidy, and then just import them into flask_app.py

I am not sure If I make it as you mention, but it return error.

Create a new flask_api.py, with same part of the code in original flask_app.py

Then, in flask_app.py, I import flask_api.py

However, I am not clear what you mean by @pp route view. If you can give a simple example will be nice.

The Flask documentation on this is pretty good, but here's a simple example.

Let's say you start off with a single-file Flask app like the one PythonAnywhere generates by default. You have a directory called mysite, containing a file called flask_app.py, which looks like this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

Let's say you've added another view:

@app.route('/goodbye')
def goodbye():
    return 'Bye!'

Now, let's say you want to put each view into a separate file. The first step is to create a directory inside your mysite directory, called flask_app (note, there's no ".py" extension there).

The next step would be create the two view files inside the new flask_app directory. Firstly, views1.py:

from flask_app import app

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

Next, views2.py:

from flask_app import app

@app.route('/goodbye')
def goodbye():
    return 'Bye!'

The next step is to create another new file inside the [edit] flask_app directory called __init__.py, containing this:

from flask import Flask

app = Flask(__name__)

import flask_app.views1
import flask_app.views2

Finally, you need to remove the original flask_app.py file, as all of its contents should now be in the other files. (Just to be safe, perhaps move it somewhere else in case you forgot to move all of the contents.)

Once you've done that, reload the web app, and it should work fine.

[edit: originally I said that the __init__.py file should be in the mysite directory, which was wrong.]

Thanks giles,

However, I have this error all veiw1.py,view2.py and init.py when it run

Traceback (most recent call last):  File "/home/vinasia/mysite/flask_app/__init__.py", line 5, in <module>    import flask_app.flask_allImportError: No module named 'flask_app'

Also, do I need to make changes for module as below to flask_app?

from flask import jsonify,abort,make_response,request

Read the Theory section at the top of this page about how Python finds modules you're trying to import: http://help.pythonanywhere.com/pages/DebuggingImportError/

Hi giles,

I follow your example and return "No module named 'flask_app' for each of the python files in the directory (in this case 3 pythons files all show the same error)

My folder and files is as below:

enter image description here

What path are you adding to sys.path in your wsgi file?

I change to

project_home = u'/home/vinasia/mysite/flask_app'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from flask_app import app as application

You don't need the "flask_app" at the end of your project_home, it should just be u'/home/vinasia/mysite/'

Hi Giles, II try with u'/home/vinasia/mysite/ but still have the same error

Traceback (most recent call last):  File "/home/vinasia/mysite/flask_app/__init__.py", line 5, in <module>    import flask_app.flask_allImportError: No module named 'flask_app'

Can I take a look at your files? We can see them from our admin interface, but we always ask for permission first.

Sure. Please take a look. Thanks

I think the problem is being caused by the file flask_app.pyc inside your mysite directory. Delete that and reload the web app, and hopefully it will work.

Hi giles,

It still return the same error. I also reloaded the web app but seems it is not the root cause. enter image description here

Hi Giles,

flask_app.pyc has been deleted. Still same error like above

Are you trying to run __init__.py? None of this should be in there- you should put it in a flask_app/app.py

Hi Conrad,

I follow what Giles suggestion above.

I rename it to app.py but still have the same error.

If it is not, let let me know which one is the correct way. Thanks

The main problem is that from flask_app/app.py or flask_app/__init__.py, if you ran the file directly from that working directory, you would import flask_app/flask_all.py and flask_app/flask_wsj.py by doing import flask_all and import flask_wsj. But for a webapp, your working directory is probably /home/vinasia/mysite, instead of /home/vinasia/mysite/flask_app

Finally, I get it run but in a complicated way, which I think get it rid of at least one file. This is my directory structure as below:

/mysite
-->flask_app
     -->__init__.py
     -->flask_all.py
     -->flask_wsj.py
-->app.py

Run __init__.py,flask_all.py and flask_wsj,py` individually in console, it will have Import error: No module named "flask_app"

Only when I run app.py, it will able to run without error. This is what in app.py

from flask import Flask

app = Flask(__name__)

import flask_app.flask_all
import flask_app.flask.wsj

This is in

 __init__.py

from flask import Flask

app = Flask(__name__)

import flask_all
import flask.wsj

flask_all.py

from flask_app import app

@app.route('/')
def hello_world():
    return 'Hello from

flask_wsj.py

from flask_app import app

@app.route('/bye')
def bye():
    return bye

So, how should arrange the file to be more organize? Is app.py and __init__.py both needed as they are so similar

no- init.py is not needed. You need to read about/learn about how importing works in python, in particular how it checks the current working directory. And understand how the current working directory changes depending on where you are running the python code from.

Also- keep in mind that if you just want to have your website online, you don't run any of this on the console at all after you have setup your webapp correctly.

Hi Giles,

Really need your further guide. As my previous post, although I make it works but I have app.py in mysite directory and init,py in flask_app directory. It is different from what you suggest in earlier post.

Also, from flask_app import app seems keep on fail for ImportError: No module named flask_app

Why is that happen? Could you take a look in my folder? Thanks a lot

Hi vinasia,

Unfortunately it is hard for us to support these type of questions which relate more to debugging code that you wrote. You may find it more helpful to get some face to face time with the code mentor guys, where they could walk you through various concepts and answer your questions in real time etc.

One thing I really strongly recommend is that you read the help page on debugging import errors carefully. That will help you understand how Python tries to find files when you have an ImportError. The important thing to keep in mind is that if you have files named such that it's ambiguous to Python which one it should load -- for example, if inside mysite you have a file called foo.py and a directory called foo, both of which could theoretically be imported using import foo -- then you're going to have problems.

Hi giles,

I try on this https://www.pythonanywhere.com/forums/topic/11374/#id_post_42851 but it not works by return Import Error: no module named flask_app.

Thus, I add __init__.py in flask_app directory. I also change from flask_app import app to from __init__ import app and return no error.

view1.py

from __init__ import app

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

view2.py

from init import app

@app.route('/goodbye') def goodbye(): return 'Bye!'

__init__.py

from flask import Flask

app = Flask(__name__)

import view1
import view2

However, I unable to see Hello from Flask' from my main page. Even I reload the webapp. sys path also point to mysite directory.

Refer stackoverflow, since it must have __init__.py to declare as module.

hence, I create another __init__.py in mysite (as you said in your example).

from flask import Flask

app = Flask(__name__)

import flask_app.view1
import flask_app.view2

But it return ImportError: No module named view1 error.

I change it to import flask_app to replace import flask_app,view1 and view 2 with no import error but still unable to get my hello world

http://bkcollecton.pythonanywhere.com/

Ah! Sorry, it looks like there was an error in my original instructions. Could you move the __init__.py file that was previously in mysite -- the one that contains this

from flask import Flask

app = Flask(__name__)

import flask_app.views1
import flask_app.views2

...into the flask_app directory?

Hi giles,

Moved __init__.py from /mysite to /mysite/flask_app will shows error ImportError: No module named flask_app.view1.

Now I have view1.py,view2.py and __init__.py inside /mysite/flask_app directory. Is this will work just like flask_app.py inside mysite directory (if I can get rid of the error)?

I have removed __init__.py from 'mysite` directory.

Yes, that certainly should work. If you check out the help page that's linked further up in this thread, you'll see that when Python looks for something called flask_app, then it will look for files called flask_app.py on your Python path, and it will also look for directories called flask_app.

Where are you seeing the ImportErrors? Are they in your website error log?

Hi Giles,

Copy from error log

2017-07-12 14:09:37,390: Error running WSGI application
2017-07-12 14:09:37,390: ImportError: cannot import name app
2017-07-12 14:09:37,390:   File "/var/www/bkcollecton_pythonanywhere_com_wsgi.py", line 17, in <module>
2017-07-12 14:09:37,391:     from flask_app import app as application

I run __init__.py from console. and it shows the ImportError: No module named flask_app.view1

It won't run from a console if you've split it into separate files, but it's strange if it's generating errors when you run it as your web app. Can I take a look at your files? We can see them from our admin interface but always ask for permission first.

yes. you can check it

You have a file called flask_app.pyc and another called __init__.py in /home/bkcollecton/mysite.

Also, your two files view1.py and view2.py both start with this:

from flask import Flask
app = Flask(__name__)

They should start with this instead:

from flask_app import app

Could you fix those, reload the website on the "Web" tab, and see if the problem is solved?

Thank Giles. It works

Excellent, thanks for confirming!