import flask
import sentimentanalyzer
app: object = flask
#app.route("/")
def default() :
return "Hello world>>!!"``
#app.route("/predictsentiment/<query>",method=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == "__main__":
app.run()
You need to import Flask class from flask module.
from flask import Flask
import sentimentanalyzer
app = Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>",methods=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == '__main__':
app.run()
I see you have not found a solution yet.
from flask import Flask
import sentimentanalyzer
app = Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>",methods=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == '__main__':
app.run()
Though the above code is correct, your error may be the initialization or the structure of the app. Please post the structure.
init.py needs to be put in a directory and the directory is called.
Try renaming your init.py to app.py, should solve the error.
As a reference the Quickstart docs here: https://flask.palletsprojects.com/en/1.1.x/quickstart/
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
You need to create an object from the Flask class to get started.
And methods needs to be plural. (ref: https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods)
Not relevant tot the question the default route has invalid syntax with the double backticks resulting in:
File "/home/tom/tmp/test.py", line 8
return "Hello world>>!!"``
^
SyntaxError: invalid syntax
Regards,
Tom
You need to import the flask class from the flask module. Check how to make minimal application here
import flask
import sentimentanalyzer
app: flask.Flask = flask.Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>")
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if _name_== " main ":
app.run()
Related
python
from flask import Flask, request, render_template
from pytube import YouTube
import pytube
app = Flask(__name__)
#app.route("/", methods=["POST", "GET"])
def find():
search1 = request.form.get("search")
print(search1)
print(type(search1))
subt = pytube.YouTube(search1) # <-- Error occurs in this line.
print(subt)
cap = subt.captions.get_by_language_code('en')
print("Video english subtitle")
print(cap.generate_srt_captions())
return render_template("sub.html")
if __name__ == "__main__":
app.run(debug=True)
Error:
TypeError: expected string or bytes-like object
results = regex.search(string)
TypeError: expected string or bytes-like object
from flask import Flask, request, render_template
from pytube import YouTube
import pytube
app = Flask(__name__)
#app.route("/", methods=["GET"])
def index():
return render_template("sub.html")
#app.route("/test", methods=["POST"])
def find():
search1 = request.form.get("search")
print(search1)
print(type(search1))
subt = pytube.YouTube(search1)
cap = subt.captions.get_by_language_code('en')
print("Video english subtitle")
print(cap.generate_srt_captions())
return render_template("sub.html", cap=cap)
if __name__ == "__main__":
app.run(debug=True)
You can use this code to download the youtube subtitle.
I am trying to mock test an endpoint that gets the time and date.
I have viewed several tutorials and python docs, but I am still getting stumped by the mock test.
Any help is appreciated greatly
from flask import Flask, redirect, url_for
import json
import urllib.request
import requests
app = Flask(__name__)
#app.route('/')
def welcome():
return "Hello"
#app.route('/<zone>')
def Endpoint(zone):
address = f"http://worldclockapi.com/api/json/{zone}/now"
response = urllib.request.urlopen(address)
result = json.loads(response.read())
time = result['currentDateTime']
return time
if __name__ == "__main__":
app.run(debug=True)
My attempt.
I think I am still calling the external element.
I want to use a fake JSON string and actually mock with that.
The first test passes when I run it. But I don't think it is a true mock.
#!/usr/bin/python
import unittest
from unittest import TestCase
from unittest.mock import patch, Mock
#name of endpoint program
import question
class TestingMock(TestCase):
#patch('question.Endpoint')
def test_call(self, MockTime):
current = MockTime()
current.posts.return_value = [
{"$id": "1", "currentDateTime": "2020-07-17T12:31-04:00", "utcOffset": "-04:00:00"}
]
response = current.posts()
self.assertIsNotNone(response)
self.assertIsInstance(response[0], dict)
#patch('question.Endpoint')
def test_response(mock_get):
mock_get.return_value.ok = True
respond = question.Endpoint()
assert_is_not_none(respond)
if __name__ == '__main__':
unittest.main()
You are conflicting with your root URL handler. Try changing #app.route('/<zone>') to #app.route('/time/<zone>'), then navigate to that url
A brief introduction to the directory structure is as follows:
__init__.py contain the application factory.
page.py
from app import app
# a simple page that says hello
#app.route('/hello')
def hello():
return 'Hello, World!'
app.py
from flaskr import create_app
app = create_app()
if __name__ == '__main__':
app.run()
When I start the server and go to the '/hello', it says 404.
What's the problem?
Here is a short solution which should run.
page.py
from flaskr import app
#app.route('/hello')
def hello():
return 'Hello'
__index__.py
from flask import Flask
app = Flask(__name__)
from flaskr import page
app.py
from flaskr import app
To run this you just need to define a Environment Variable on the Commandline like this:
export FLASK_APP=microblog.py
And then run it with
flask run
The way you have structured your code is not right. That's the reason you are not able to access your "/hello" API.
Let's assume that you run the app.py file. In this case, you haven't imported page.py right? So, how will the app.py know that there is a route defined in page.py?
Alternatively, let's assume you run page.py. In this case, when you do an "from app import app" , the main definition does not get executed. Here too, the route will now be present, but the app will not be run, thereby you will be unable to access your API.
The simplest solution would be to combine the contents of app.py and page.py into a single file.
Hear is my code:
from flask import Flask
from flask import Markup
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route("/")
def chart():
labels = ["2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4"]
values = [9,6,6,10,9,7,5,4,10,6,10,8]
return render_template('chart.html', values=values, labels=labels)
#app.route("/chart")
def chart():
labels = ["2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4"]
values = [9,6,6,10,9,7,5,4,10,6,10,8]
return render_template('chart.html', values=values, labels=labels)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001)
The first #app.route("/") works correctly the second does not disappear any Chart like the first one. it disappears just some text of HTML. Any one can help?
First, you don't need to import Flask twice so you can delete one line of
from flask import Flask
The reason it's not working is because you defined two of the same functions 'chart()'. There also seems to be something wrong with the name 'chart' as a route, if you change that, it should be working.
I did everything according to the flask documentation, but I always get the error 404. I really don't get what I am doing wrong. Perhaps, someone can look at my code and give me a push in the direction of my mistake? It would be too generous, I am really stuck here for hours now and I am almost at the point to give up again. It is so frustrating.
my app:
import flask
app = flask.Flask(__name__)
def main():
register_blueprints()
app.run(debug=True)
def register_blueprints():
from pypi_org.views import home_views
from pypi_org.views import package_views
app.register_blueprint(package_views.blueprint)
app.register_blueprint(home_views.blueprint)
if __name__ == '__main__':
main()
my home_views.py file
import flask
import pypi_org.services.package_service as package_service
blueprint = flask.Blueprint('home', __name__, template_folder='templates')
#blueprint.route('/')
def index():
test_packages = package_service.get_latest_packages()
return flask.render_template('home/index.html', packages=test_packages)
#blueprint.route('/about')
def about():
return flask.render_template('home/about.html')
I found the answer to this in the 'final' github files provided for the course (see the link provided by OP), there's an addition of a couple lines in app.py:
if __name__ == '__main__':
main()
else:
register_blueprints()
Perhaps simplify app.py:
import flask
from pypi_org.views import home_views
from pypi_org.views import package_views
app = flask.Flask(__name__)
app.register_blueprint(package_views.blueprint)
app.register_blueprint(home_views.blueprint)
if __name__ == '__main__':
print (app.url_map)
app.run(debug=True)
Note the addition of the second last line prints all the URL routes to the terminal when you run the application, which helps for debugging.