justpy app don't work on AWS Lightsail; no error but also no page visible - hosting

A python file with this code:
import justpy as jp
def hello_world():
wp = jp.WebPage()
jp.Hello(a=wp)
return wp
jp.justpy(hello_world)
A justpy.env file with this parameters:
HOST = '0.0.0.0'
PORT = 8000
A Lightsail Ubuntu VM with static URL runs the file with output on console:
ubuntu#ip-xy:~$ python3 run.py
/home/ubuntu/.local/lib/python3.8/site-packages/justpy
Module directory: /home/ubuntu/.local/lib/python3.8/site-packages/justpy, Application dire
ctory: /home/ubuntu
JustPy ready to go on http://0.0.0.0:8000
Page not shown. What is missing?
What is missing? I suffer with this.

Related

How can I periodically delete the contents of a folder ("uploads") related to my flask app on heroku

I need to periodically delete files of an uploads folder on heroku in python.
I've tried the heroku scheduler but I am constantly getting a fileNotFound error which I am unable to fix.
from flask_script import Manager
from app import app
manager = Manager(app)
#manager.command
def hello():
folder_path = '/uploads/'
for file_object in os.listdir(folder_path):
file_object_path = os.path.join(folder_path, file_object)
if os.path.isfile(file_object_path):
os.unlink(file_object_path)
else:
shutil.rmtree(file_object_path)

Why won't my flask command work on Heroku?

I have a simple CLI took in Flask that I use to create dummy data. It works fine on my local machine but not on Heroku. Here's a terminal session:
(venv) $ flask create-dummy-data
(venv) $ git push staging master
Everything up-to-date
(venv) $ heroku run bash --remote staging
Running bash on ⬢ app-name... up, run.8533 (Free)
~ $ flask create-dummy-data
Usage: flask [OPTIONS] COMMAND [ARGS]...
Try "flask --help" for help.
Error: No such command "create-dummy-data".
Here's my app/cli.py file:
import lorem
from app import db
from app.models import Survey, Question, Option, Answer, Response
def register(app):
#app.cli.command()
def create_dummy_data():
"""Create lorem ipsum questions and answers for testing."""
survey = Survey()
db.session.add(survey)
for _ in range(3):
question = Question(survey=survey, category='likert', question=lorem.sentence())
db.session.add(question)
for _ in range (2):
question = Question(survey=survey, category='word', question=lorem.sentence())
db.session.add(question)
db.session.commit()
And my run.py file:
from app import create_app, db, cli
from app.models import Survey, Question, Option, Answer, Response
app = create_app()
cli.register(app)
#app.shell_context_processor
def make_shell_context():
return {'db': db,
'Survey': Survey,
'Question': Question,
'Option': Option,
'Answer': Answer,
'Response': Response
}
Why would this work locally but not on the Heroku shell?
It was the simplest thing: Heroku didn't have $FLASK_APP set in the staging environment's variables. Adding that allowed the command line tool to run.

D3, loading a csv file, filepath issue ? [duplicate]

I'm just learning d3, and I'm attempting to import data from a CSV file, but I keep getting the error "XMLHttpRequest cannot load file:///Users/Laura/Desktop/SampleECG.csv. Cross origin requests are only supported for HTTP. ". I've searched for how to fix this error and have ran it on a local web server, but I haven't found a solution that works for d3.v2.js. Here's a sample of the code:
var Time = []
ECG1 = []
d3.csv("/Desktop/d3Project/Sample.csv", function(data)
{
Time = data.map(function(d) {return [+d["Time"]];});
ECG1 = data.map(function(d) {return [+d["ECG1"]];});
console.log(Time)
console.log(ECG1)
});
Any help will be much appreciated.
This confused me too (I am also a d3 beginner).
So, for some reason, web browsers are not happy about you loading local data, probably for security reasons or something. Anyways, to get around this, you have to run a local web server. This is easy.
In your terminal, after cd-ing to your website's document root (thanks #daixtr), type:
python -m SimpleHTTPServer 8888 &
Okay, now as long as that terminal window is open and running, your local 8888 web server will be running.
So in my case, originally the web page I was working on was called
file://localhost/Users/hills/Desktop/website/visualizing-us-bls-data-inflation-and-prices.html
When I opened it in chrome. To open up my page on my local web server, I just typed (into the chrome search bar):
http://localhost:8888/Desktop/website/visualizing-us-bls-data-inflation-and-prices.html
Now, reading in CSVs should work. Weird, I know.
To those using built-in python webserver and who are still experiencing issues, do REMEMBER and make sure that you run the "python -m SimpleHTTPServer 8888" invocation at the correct path of which you consider to be your DocumentRoot. That is, you cannot just run 'python -m SimpleHTTPServer 8888' anywhere. You have to actually 'cd /to/correct/path/' containing your index.html or data.tsv and then from there run 'python -m SimpleHTTPServer 8888'.
Also, just learning D3 for school work. I was trying to run this simple D3 example:
https://gist.github.com/d3noob/b3ff6ae1c120eea654b5
I had the same problem as OP re: loading data using Chrome browser. I bet the great solution Hillary Sanders posted above was re: Python 2.X.
My answer is re: Python 3.X [OS: Ubuntu 16x]:
Open a terminal window within the root directory of your project, then run:
python3 -m http.server
It will serve HTTP on port 8000 by default unless it is already taken, in that case to open another port, e.g. 7800, run:
python3 -m http.server 7800
Then, on your Chrome browser address bar type:
localhost:8000
The above worked for me because I only had an index.html page in my root folder. In case, you have a HTML page with a different name, type the whole path to that local HTML page and it should work also. And, you should be able to see the graph created from the data set in my link (that must be in a folder like data/data.csv). I hope this helps. :-)
Use Firefox, idk what Chrome tries to accomplish

Flask with MongoDB using MongoKit to MongoLabs

I am a beginner and I have a simple application I have developed locally which uses mongodb with mongoKit as follows:
app = Flask(__name__)
app.config.from_object(__name__)
customerDB = MongoKit(app)
customerDB.register([CustomerModel])
then in views I just use the CustomerDB
I have put everything on heroku cloud but my database connection doesn't work.
I got the link I need to connect by:
heroku config | grep MONGOLAB_URI
but I am not sure how to pull this. I looked at the following post, but I am more confused
How can I use the mongolab add-on to Heroku from python?
Any help would be appreciated.
Thanks!
According to the documentation, Flask-MongoKit supports a set of configuration settings.
MONGODB_DATABASE
MONGODB_HOST
MONGODB_PORT
MONGODB_USERNAME
MONGODB_PASSWORD
The MONGOLAB_URI environment setting needs to be parsed to get each of these. We can use this answer to the question you linked to as a starting point.
import os
from urlparse import urlsplit
from flask import Flask
from flask_mongokit import MongoKit
app = Flask(__name__)
# Get the URL from the Heroku setting.
url = os.environ.get('MONGOLAB_URI', 'mongodb://localhost:27017/some_db_name')
# Parse it.
parsed - urlsplit(url)
# The database name comes from the path, minus the leading /.
app.config['MONGODB_DATABASE'] = parsed.path[1:]
if '#' in parsed.netloc:
# If there are authentication details, split the network locality.
auth, server = parsed.netloc.split('#')
# The username and password are in the first part, separated by a :.
app.config['MONGODB_USERNAME'], app.config['MONGODB_PASSWORD'] = auth.split(':')
else:
# Otherwise the whole thing is the host and port.
server = parsed.netloc
# Split whatever version of netloc we have left to get the host and port.
app.config['MONGODB_HOST'], app.config['MONGODB_PORT'] = server.split(':')
customerDB = MongoKit(app)

gevent-socketio + Flask + Gunicorn

Can I use gevent-socketio with Flask, running under Gunicorn, and still enjoy the nice exception printing, debugger, and reload capability that Flask offers? How would my gunicorn worker and WSGI app class look like?
I've got the exact same problem so I solved it by using watchdog.
pip install watchdog
together with this command:
watchmedo shell-command --patterns="*.py*;;*.less;*.css;*.js;*.txt;*.html" --recursive --command='kill -HUP `cat /tmp/gunicorn.pid` && echo "Reloading code" >> /tmp/gunicorn.log' ~/projectfolder
It requires (well, not really, but I point "Reloading code" into the same logfile so It's a nice thing to have) that you daemonize the gunicorn process, which I do like this:
gunicorn_config.py
workers = 2
worker_class = 'socketio.sgunicorn.GeventSocketIOWorker'
bind = '0.0.0.0:5000'
pidfile = '/tmp/gunicorn.pid'
debug = True
loglevel = 'debug'
errorlog = '/tmp/gunicorn.log'
daemon = True
Start the application:
gunicorn run:app -c gunicorn-config.py
View the log:
tail -f /tmp/gunicorn.log
From this point everything should be reloaded with each change in your project.
It's a bit complicated but since gunicorn with a worker (or the built in socketio-server) doesn't have any reloading capabilities I had to do it like this.
It's a different approach compared to the decorator solution in the other answer but I like to keep the actual code clean from development specific solutions. Both accomplish the same thing so I guess you'll just have to pick the solution you like. :)
Oh, as an added bonus you get to use the production server in development which means both environments match each other.
I've been looking into this subject lately. I don't think you can easily use autoreload feature with Flask + gevent-socket.io + Gunicorn. Gunicorn is a production server that does not allow such features natively.
However, I found a nice solution for my development server : user SocketIOServer provided with the library and a Flask snippet for autoreload. Here is the startup script (runserver.py) :
from myapp import app
from gevent import monkey
from socketio.server import SocketIOServer
import werkzeug.serving
# necessary for autoreload (at least)
monkey.patch_all()
PORT = 5000
#werkzeug.serving.run_with_reloader
def runServer():
print 'Listening on %s...' % PORT
ws = SocketIOServer(('0.0.0.0', PORT), app, resource="socket.io", policy_server=False)
ws.serve_forever()
runServer()
This solution is inspired from : http://flask.pocoo.org/snippets/34/
I've made some tweaks to Werkzeug debugger so it now works with socket.io namespaces, see below and enjoy :)
https://github.com/aldanor/SocketIO-Flask-Debug

Resources