Forums

Trouble hosting flask app on pythonanywhere

I am a first time user of pythonanywhere

I first started by doing a git clone of my code from github through the bash console. I did not use a virtual environment. My WSGI app was invoked in my app.py file. Also, my code uses sqlalchemy to interact with my database.

Basically, the flask app was like a custom api that returned JSON for GET and POST requests and I am having trouble viewing the JSON output. I am not sure what exactly I am doing wrong or missing.

Code in app.py file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Base, Quote
from flask import request
from flask import abort
import json

#connect to database

engine = create_engine("sqlite:///quotes.db")

Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

app = Flask(__name__)

@app.route("/trumptext/api/quotes", methods=["GET"])
def get_quotes():
    quoteList = session.query(Quote).all()
    result = []
   for q in quoteList:
       my_dict = {}
       my_dict["id"] = q.id
       my_dict["quote"] = q.quote
       result.append(my_dict)
   return json.dumps(result,ensure_ascii=False).encode('utf8')

@app.route("/trumptext/api/quotes", methods=["POST"])
def add_quote():
    if not request.json or not "quote" in request.json:
        abort(400)
    new_quote = request.json["quote"]
    q = Quote(quote=new_quote)
    session.add(q)
    session.commit()
    quoteList = session.query(Quote).all()
    last = quoteList[-1]
    result = []
    my_dict = {}
    my_dict["id"] = last.id
    my_dict["quote"] = last.quote
    result.append(my_dict)
    return json.dumps(result,ensure_ascii=False).encode('utf8'), 201


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

Also, code in /var/www/nnelson_pythonanywhere_com_wsgi.py:

import os
import sys

path = '/home/nnelson/trumptextapi'
if path not in sys.path:
    sys.path.append(path)

from app import app as application

If I enter something like : http://nnelson.pythonanywhere.com/trumptext/api/quotes (to perform a GET request)

It should ideally return all the quotes stored in the quotes.db database in JSON format, however all I get it output that looks like this: [] I tested my code on localhost using the curl tool and it works just fine. I am having trouble hosting it though

Any help is appreciated.

You're using a relative path to your database, so it's probably looking at a database that you don't expect. Use a full path to the database or make it relative to the path of your app.py file so that you know where it's getting the database from.