"GET / HTTP/1.1" 404 in Python Flask - mysql

This is my code i m getting error on browser is The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. my file name is app.py
from flask import Flask, render_template, json, request
from datetime import datetime
from threading import Timer
app = Flask(__name__)
x=datetime.today()
y=x.replace(day=x.day+1, hour=12, minute=52, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
if __name__ == "__main__":
app.run(port=5004)

Before your hello_world function add #app.route('/') such that your code looks as follows,
#app.route('/')
def hello_world():
print "hello world"

Related

BlockingIOError: [Errno 11] write could not complete without blocking

Please help, I have developed this scraper API and it works with internal commands in Pythionanywhere, but when I try to access it using my use account URL, it gives the error: [errno 11] and I have searched for solutions, I co[enter image description here](https://i.stack.imgur.com/cs9T6.png)uldn't find any.
I was expecting a JSON output as it did on the internal server.
#from requests_html import HTMLSession
import json
import requests
class Scraper():
def scrapedata(self, tag):
url = "https://www.etenders.gov.za/Home/TenderOpportunities/?status=1"
headers = {'user-agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
data = response.json()
file_urs = []
for e in data:
item = {
'province': (f"{e['province']}"),
'id' : (f"{e['tender_No']}"),
}
print(file_urs)
file_urs.append(item)
return file_urs
quotes = Scraper()
quotes.scrapedata('cat')
from flask import Flask
import json
from scrape import Scraper
app = Flask(name)
quotes = Scraper()
#app.route('/', methods =['GET', 'POST'])
async def read_item(cat):
json_dumps = json.dumps.scrapedata(cat)
return json_dumps
#return quotes.scrapedata(cat).jon()
from flask import Flask
import json
from scrape import Scraper
app = Flask(name)
quotes = Scraper()
#app.route('/', methods =['GET', 'POST'])
async def read_item(cat):
json_dumps = json.dumps.scrapedata(cat)
return json_dumps
#return quotes.scrapedata(cat).jon()
I was expecting a JSON output as it did on the internal server.

Same dash dashboard template with different dataset inside a flask app. How to do it?

I'm looking for the simplest way to generate the same dash dashboard X times with different dataset.
Each dashboard is a single page and the main app is a flask app.
The goal is to have a dashboard template running on different dash instance with different dataset.
I started with the following code, but I'm struggling when dash pages include callbacks i.e when html.Div([html.H1('Hi there, I am app1 for reports')]) turns into a bigger function with callback
import dash
import dash_html_components as html
from flask import Flask, render_template, redirect
from werkzeug.middleware.dispatcher import DispatcherMiddleware
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello from Flask!'
#app.route('/test2')
def t2():
return render_template('test2.html')
dash_app1 = dash.Dash(__name__, server = app, url_base_pathname='/dashboard/' )
dash_app2 = dash.Dash(__name__, server = app, url_base_pathname='/reports/')
dash_app1.layout = html.Div([html.H1('Hi there, I am app1 for reports')])
dash_app2.layout = html.Div([html.H1('Hi there, I am app2 for reports')])
#app.route('/dashboard')
def render_dashboard():
return redirect('/dash1')
#app.route('/reports')
def render_reports():
return redirect('/dash2')
app = DispatcherMiddleware(app, {
'/dash1': dash_app1.server,
'/dash2': dash_app2.server
})
So my question is what is the best way/architecture to manage muti dash dashboards, based on the same template, running different data ?
In case it might help, I found a solution encapsulating the layout, callbacks and return function into a class.
flask_app.py
from flask import Flask, render_template, redirect
import dash
from apps.dashboard1 import Dashboard1
from apps.dashboard2 import Dashboard2
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello from Flask!'
#app.route('/test')
def test():
return render_template('test.html')
dash_app1 = dash.Dash(__name__, server = app, url_base_pathname='/dashboard1/' )
dash_app1.config.suppress_callback_exceptions = True
dash_app1.layout = Dashboard1(dash_app1).layout
#app.route('/dashboard1')
def render_dashboard():
return redirect('/dash1')
dash_app2 = dash.Dash(__name__, server = app, url_base_pathname='/dashboard2/')
dash_app2.config.suppress_callback_exceptions = True
dash_app2.layout = Dashboard2(dash_app2).layout
#app.route('/dashboard2')
def render_dashboard2():
return redirect('/dash2')
if __name__ == '__main__':
app.run(debug=True)
apps/dashboard1.py
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
class Dashboard1:
def __init__(self, app_dependency):
self.app_dependency = app_dependency
html.P("Your code here"),
dcc.Dropdown(...),
...
dcc.Graph(id="pie-chart"),
])
#self.app_dependency.callback(
Output("pie-chart", "figure"),
Input('organisations', 'value'))
def update_output_div(selected_org):
your_update_function
return your_outputs

i am trying to create a simple api to recieve any format of json data but getting 400 bad request.. please have a look to my code and correct

from flask import Flask, abort, request
import json
app = Flask(__name__)
#app.route('/data', methods=['POST'])
def data():
if not request.json:
abort(400)
print(request.json)
return json.dumps(request.json)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001, debug=True)
i want to send all my post request to another endpoint at localhost:8000.. please suggest the correctionsenter code here
I tried run your code, it works fine, here is my exmaple:
Server same as yours. One suggestion about your code: .json attribute has been deprecated, you should use the request.get_json() method.
from flask import Flask, abort, request
import json
app = Flask(__name__)
#app.route('/data', methods=['POST'])
def data():
if not request.json:
abort(400)
print(request.json)
return json.dumps(request.json)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001, debug=True)
client:
import requests
res = requests.post('http://localhost:5001/data', json={"mytext":"test"})
if res.ok:
print(res.json())
I guessed you don't fire the right HTTP request. for exmaple, do you add attribute Content-Type: application/json in your http header?

creating a REST API without Flask in python

I want to create a REST API without using Flask. I have created once using Flask as shown below but now I want to try without Flask. I came to know that urllib is one of the packages for doing it but not sure how to do. Even if there is some way other than urllib then that is also fine.
from werkzeug.wrappers import Request, Response
import json
from flask import Flask, request, jsonify
app = Flask(__name__)
with open ("jsonfile.json") as f:
data = json.load(f)
#data=f.read()
#app.route('/', methods=['GET', 'POST'])
def hello():
return jsonify(data)
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 9000, app)
You can try something like this
import json
import http.server
import socketserver
from typing import Tuple
from http import HTTPStatus
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer):
super().__init__(request, client_address, server)
#property
def api_response(self):
return json.dumps({"message": "Hello world"}).encode()
def do_GET(self):
if self.path == '/':
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(bytes(self.api_response))
if __name__ == "__main__":
PORT = 8000
# Create an object of the above class
my_server = socketserver.TCPServer(("0.0.0.0", PORT), Handler)
# Star the server
print(f"Server started at {PORT}")
my_server.serve_forever()
And testing like this
→ curl http://localhost:8000
{"message": "Hello world"}%
but keep in mind that this code is not stable and just sample
You shall take an existing web server and use WSGI compatible app, for example, for Apache HTTP 2.2
Install mod_wsgi (just search how to install mod_wsgi in your operating system)
Configure mod_wsgi in Apache httpd.conf
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias /wsgi /var/www/wsgi/myapp.wsgi
Write myapp.wsgi
The code for myapp.wsgi must call the second argument once in this way:
def application(environ, start_response):
status = '200 OK'
output = b'{"message": "Hello world"}'
response_headers = [('Content-type', 'application/json'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]

HTMLTestRunner is not working

I'm trying to generate an HTML report from my Unittests of Python3.6. I'm using the HTMLTestRunner library.
Here are my unit tests:
#!/usr/bin/env python
import unittest
import boto3
import warnings
import HTMLTestRunner
class SecurityGroupTest(unittest.TestCase):
def setUp(self):
session = boto3.Session(profile_name='default')
self.ec2_clt = session.client('ec2')
def test_delete_03(self):
response = self.ec2_clt.describe_security_groups()
self.assertEqual(len(response['SecurityGroups']), 0)
if __name__ == "__main__":
HTMLTestRunner.main()
When I run the tests, nothing is generated. What am I missing here?