Flask web app crashes in Heroku, is fine in my computer server - flask

It was find when it was a simple "Hello world" web, but I want to add this Dash-pivottable from plotly and it doen't work.
I get this error in the Heroku logs:
at=error code=H10 desc="App crashed" method=GET path="/" host=flasktabla.herokuapp.com request_id=** fwd="201.239.88.79" dyno=web.1 connect=5001ms service= status=503 bytes= protocol=https
app.py:
from flask import Flask
import dash
import dash_html_components as html
import dash_pivottable
server = Flask(__name__)
app = dash.Dash(__name__)
server = app.server
app.layout = html.Div(
dash_pivottable.PivotTable(
data=[
['Animal', 'Count', 'Location'],
['Zebra', 5, 'SF Zoo'],
['Tiger', 3, 'SF Zoo'],
['Zebra', 2, 'LA Zoo'],
['Tiger', 4, 'LA Zoo'],
],
cols=["Animal"],
rows=["Location"],
vals=["Count"]
)
)
if __name__ == "__main__":
app.run_server(debug=True)
#server.route("/")
def my_dash_app():
return app.index()
requirements.txt:
Click==7.1.2
Flask==1.1.2
gunicorn==20.1.0
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==1.1.1
Werkzeug==1.0.1
dash-pivottable==0.0.2
Procfile:
web: gunicorn app:app
Thanks.

This is probably a error in your Procfile.
Change your Procfile to this:
web: gunicorn --bind 0.0.0.0:$PORT flaskapp:app

Related

Flask webserver in Heroku returning 404 when serving CSS files

Website works for everything except CSS files. Static images works, static javascript works, favicon works, but CSS returns 404. I've tried different browsers and cache-reload on web browser.
Application logs:
2021-08-04T15:17:38.416574+00:00 heroku[router]: at=info method=GET
path="/static/css/index.css" host=redacted fwd="82.196.112.61"
dyno=web.1 connect=1ms service=7ms status=404 bytes=2332 protocol=https
2021-08-04T15:17:38.424598+00:00 heroku[router]: at=info method=GET
path="/static/js/bootstrap.bundle.js" host=redacted fwd="82.196.112.61"
dyno=web.1 connect=0ms service=27ms status=200 bytes=208248 protocol=https
This is my project structure. It works fully well locally, but as soon as I push it to Heroku the CSS fails to be served.
Project structure:
App.py:
from app import app
if __name__ == "__main__":
app.run(host='0.0.0.0',
port=33507,
use_reloader = True)
__init__.py:
from flask import Flask, send_from_directory
from whitenoise import WhiteNoise
app = Flask(__name__)
# Allows the app to identify the static folder
app.static_folder = 'static'
app.wsgi_app = WhiteNoise(
app.wsgi_app,
root='static/')
#app.route("/static/<path:path>")
def static_dir(path):
return send_from_directory("static", path)
#Configuration of application, see configuration.py, choose one and uncomment.
configuration = 'app.configuration.ProductionConfig'
#configuration = 'app.configuration.DevelopmentConfig'
app.config.from_object(configuration)
print('Running server on ' + app.config['ENV'] + '.')
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
print('Running database at', app.config['SQLALCHEMY_DATABASE_URI'])
from app import views, models
db.create_all()
SOLVED
The issue was rooted in heroku being case-sensitive while Github is not. Even though you change the case on a folder locally, it does not get commited and pushed to Github, and this then propagates to Heroku.
TL;DR: Check that your folders are persistent in it's letter case, locally, on Github, and in Heroku.
Github:
Code:

Flask restful API deploy on the Heroku with the dependencies

I am getting below error when I deploy the Flask application on Heroku.
2020-10-11T05:28:50.452007+00:00 app[web.1]: * Serving Flask app "app" (lazy loading)
2020-10-11T05:28:50.452050+00:00 app[web.1]: * Environment: production
2020-10-11T05:28:50.452113+00:00 app[web.1]: WARNING: This is a development server. Do not use it in a production deployment.
2020-10-11T05:28:50.452210+00:00 app[web.1]: Use a production WSGI server instead.
2020-10-11T05:28:50.452246+00:00 app[web.1]: * Debug mode: on
2020-10-11T05:28:50.462079+00:00 app[web.1]: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2020-10-11T05:29:48.134889+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2020-10-11T05:29:48.151545+00:00 heroku[web.1]: Stopping process with SIGKILL
2020-10-11T05:29:48.224518+00:00 heroku[web.1]: Process exited with status 137
2020-10-11T05:29:48.266775+00:00 heroku[web.1]: State changed from starting to crashed
2020-10-11T10:08:59.088712+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=qbdeployment.herokuapp.com request_id=7bf072d9-ed06-46ff-b463-797f74881a32 fwd="122.179.230.179" dyno= connect= service= status=503 bytes= protocol=https
2020-10-11T10:08:59.829982+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=qbdeployment.herokuapp.com request_id=7c158f7d-6ce3-44fe-87fd-24adfbfbd43e fwd="122.179.230.179" dyno= connect= service= status=503 bytes= protocol=https
2020-10-11T10:09:10.062949+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=qbdeployment.herokuapp.com request_id=fc43dec0-8976-45a6-bec7-87e749125436 fwd="122.179.230.179" dyno= connect= service= status=503 bytes= protocol=https
2020-10-11T10:09:10.678640+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=qbdeployment.herokuapp.com request_id=c61189c8-4ca8-4e73-8697-8279f69fefef fwd="122.179.230.179" dyno= connect= service= status=503 bytes= protocol=https
yes i read the message, but the issue is i am calling the API to get the result
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
# Create some test data for our catalog in the form of a list of dictionaries.
#app.route('/', methods=['GET'])
def home():
return '''<h1>WELCOME</h1>
<p>Get all pppp hhhh insterted and delected text from the word document.</p>'''
#app.route('/api', methods=['GET'])
def api_id():
import requests
import xmltodict
import pprint
import json
from zipfile import ZipFile
from urllib.request import urlopen
from io import BytesIO
# from zipfile import *
from bs4 import BeautifulSoup
import pandas as pd
if 'Id' in request.args:
Id = request.args['Id']
print(type(Id))
else:
return "Error: No id field provided. Please specify an id."
results = []
url='https://bps.quickbase.com/db/****?a=API_GetRecordInfo&rid='+Id+'&fmt=structured&usertoken=****'
#url='https://builderprogram-pverma.quickbase.com/db/bqscz87a5?a=API_GetRecordInfo&rid='+Id+'&fmt=structured&usertoken=b5fdma_nx3z_pzc2d4b2uvnihbayfyd8bk8swsk'
response = requests.request("GET", url)
print(response)
r=response.text.encode('utf8')
print(r)
pp = pprint.PrettyPrinter(indent=4)
data=json.dumps(xmltodict.parse(r))
data1=json.loads(data)
for i in data1.values():
for j in i['field']:
if j['fid']=="11":
Document=j['value']
if j['fid']=="3":
R_Id=j['value']
Mapped_data={R_Id :Document}
# print(Mapped_data)
# return Mapped_data
track_changed_for_del=[]
track_changed_for_ins=[]
for key, value in Mapped_data.items():
wordfile=urlopen(value).read()
wordfile=BytesIO(wordfile)
document=ZipFile(wordfile)
document.namelist()
xml_content=document.read('word/document.xml')
wordobj=BeautifulSoup(xml_content.decode('utf-8'),'xml')
key_record=key
for dl in wordobj.find_all('w:del'):
Text=dl.text
author=dl.get('w:author')
Date=dl.get('w:date')
Type='Deleted Text'
ID=dl.get('w:id')
ID=int(ID)
dataDict_del = { 'Text':Text,'Author':author,'Date':Date,'Type':Type,'ID':ID,'Record_Id':key_record}
print(dataDict_del)
track_changed_for_del.append(dataDict_del)
for ins in wordobj.find_all('w:ins'):
Text=ins.text
author=ins.get('w:author')
Date=ins.get('w:date')
Type='Inserted Text'
ID=ins.get('w:id')
ID=int(ID)
dataDict_ins = { 'Text':Text,'Author':author,'Date':Date,'Type':Type,'ID':ID,'Record_Id':key_record}
track_changed_for_ins.append(dataDict_ins)
df_track_changed_ins= pd.DataFrame(track_changed_for_ins)
df_track_changed_del= pd.DataFrame(track_changed_for_del)```

Django Channel 2 with Daphne on Heroku crash on starting

I created a django app using Channels 2 on heroku but it crash on starting with 503 error code.
2020-04-07T10:05:35.226253+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.mysite.com request_id=317bfbe6-9055-4957-9fbb-8190616c3964 fwd="" dyno= connect= service= status=503 bytes= protocol=https
Procfile :
release: python manage.py migrate
web : daphne myproject.asgi:application --port $PORT --bind 0.0.0.0 -v2
worker: python manage.py runworker channels -v2
settings.py
ASGI_APPLICATION = 'myproject.routing.application'
# Channels
CHANNEL_LAYERS = {
"default": {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
"CONFIG": {
"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
},
}
asgi.py
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
django.setup()
application = get_default_application()
Have you created an instance of the process web in heroku?
You can do it in command line : heroku ps:scale worker=1
Give worker in Procfile as:
worker: python manage.py runworker channels --settings=<project-name>.settings -v2
Your Procfile should have this instead :
release: python3 manage.py makemigrations && python3 manage.py migrate
web: daphne domecode.asgi:application --port $PORT --bind 0.0.0.0 -v2
worker: python3 manage.py runworker channel_layer -v2
channel_layer instead of channels. Why? Well, look at your settings again, you've declared CHANNEL_LAYER there which you run locally on a Redis instance on Docker. However when deploying you can't run it on Docker ( I mean you technically can use Docker Swarms on Digital Ocean or AWS, I'm not sure how it works on Heroku ) so you need to change it to channel_layer.

Django redirect interrupted by browser?

I have a very simple view that is purposed to track a user's click and redirect them to an external page:
def redirect_view(request, uu_id):
my_model = MyModel.objects.get(uuid = uu_id)
my_model.clicked_link = True
my_model.save()
return redirect('https://www.some-other-site.com')
For about half of the users that interact with this view it works perfectly! Our logs show a 302 response and then nothing further from the user.
For the other half of our users they are strangely redirected to the base url of our site in http, then because we have SECURE_SSL_REDIRECT = True they are redirected to https, and finally because they are not authenticated they are redirected for authentication.
Our logs for this type of user look something like this:
Feb 21 10:04:51 myapp heroku/router: at=info method=GET path="/redirect-url" host=mysite.com request_id=123 fwd="..." dyno=web.1 connect=0ms service=25ms status=302 bytes=268 protocol=https
Feb 21 10:04:51 myapp heroku/router: at=info method=GET path="/" host=mysite.com request_id=456 fwd="..." dyno=web.1 connect=1ms service=3ms status=301 bytes=262 protocol=http
Feb 21 10:04:52 myapp heroku/router: at=info method=GET path="/" host=mysite.com request_id=789 fwd="..." dyno=web.1 connect=0ms service=2ms status=302 bytes=360 protocol=https
There is nothing in our code that would suggest a redirect to our base url so my only thought is that they have some sort of browser setting that limits external redirects.
Could this in any way be caused by Django?
If this is not a Django issue what is causing it? and what would be a good work-around?

Heroku Django deployment is successful but the application url is showing "Application error"

I am able to deploy to create and deploy the Django app on Heroku. My app runs locally. But when I run heroku open I get the default error message
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allistic_server.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
Procfile
web:gunicorn server.wsgi --log-file
requirements.txt
Django==2.0.8
djangorestframework==3.9.1
gunicorn==19.7.2
whitenoise==3.6
heroku logs --tail
2019-03-05T19:14:22.539357+00:00 heroku[run.5495]: Awaiting client
2019-03-05T19:14:22.621479+00:00 heroku[run.5495]: Starting process with command `python3 manage.py migrate`
2019-03-05T19:14:30.032541+00:00 heroku[run.5495]: State changed from up to complete
2019-03-05T19:14:30.012744+00:00 heroku[run.5495]: Process exited with status 0
2019-03-05T19:14:32.734812+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=allistic-server.herokuapp.com request_id=8ad9d0a4-c449-4d43-8c0d-dbca27057c15 fwd="1.186.161.14" dyno= connect= service= status=503 bytes= protocol=https
2019-03-06T03:48:06.561682+00:00 app[api]: Starting process with command `bash` by user nedheesh.hasija#gmail.com
2019-03-06T03:48:12.189344+00:00 heroku[run.5469]: Awaiting client
2019-03-06T03:48:12.352258+00:00 heroku[run.5469]: State changed from starting to up
2019-03-06T03:48:42.200755+00:00 heroku[run.5469]: State changed from up to complete
2019-03-06T03:48:42.208643+00:00 heroku[run.5469]: Error R13 (Attach error) -> Failed to attach to process
2019-03-06T03:48:42.208643+00:00 heroku[run.5469]: Process exited with status 128
2019-03-06T03:49:06.415742+00:00 app[api]: Starting process with command `python3 manage.py makemigrations server` by user nedheesh.hasija#gmail.com
2019-03-06T03:49:11.116008+00:00 heroku[run.8566]: State changed from starting to up
2019-03-06T03:49:10.945200+00:00 heroku[run.8566]: Awaiting client
2019-03-06T03:49:10.978874+00:00 heroku[run.8566]: Starting process with command `python3 manage.py makemigrations server`
2019-03-06T03:49:15.768377+00:00 heroku[run.8566]: State changed from up to complete
2019-03-06T03:49:15.755742+00:00 heroku[run.8566]: Process exited with status 0
2019-03-06T03:49:27.418851+00:00 app[api]: Starting process with command `python3 manage.py migrate` by user nedheesh.hasija#gmail.com
2019-03-06T03:49:32.142089+00:00 heroku[run.4691]: Awaiting client
2019-03-06T03:49:32.162472+00:00 heroku[run.4691]: Starting process with command `python3 manage.py migrate`
2019-03-06T03:49:32.288884+00:00 heroku[run.4691]: State changed from starting to up
2019-03-06T03:49:37.323528+00:00 heroku[run.4691]: State changed from up to complete
2019-03-06T03:49:37.313173+00:00 heroku[run.4691]: Process exited with status 0
2019-03-06T03:50:31.399736+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=allistic-server.herokuapp.com request_id=626bda41-2cdc-44ce-95f1-f06440bb84a8 fwd="1.186.161.14" dyno= connect= service= status=503 bytes= protocol=https
2019-03-06T03:50:31.727399+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=allistic-server.herokuapp.com request_id=c1ea577e-a38f-487b-bf0a-557d1494155f fwd="1.186.161.14" dyno= connect= service= status=503 bytes= protocol=https
2019-03-06T03:50:31.732747+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=allistic-server.herokuapp.com request_id=00a45ba6-bf19-4a9f-8ce2-f41e585ae165 fwd="1.186.161.14" dyno= connect= service= status=503 bytes= protocol=https
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allistic_server.settings")
I can see that you project is called as allistic_server, but in the procfile you have mentioned 'server.wsgi' which is not a valid path. Change this
web:gunicorn server.wsgi --log-file
to
web:gunicorn allistic_server.wsgi --log-file