"Permission denied" while using flask - python

I am trying to make a messenger bot using Wit.ai. For that I need a webhook. I am using ngrok, and this is just a test file but I am getting this error.
This is the error I am getting.
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
Traceback (most recent call last):
File "app.py", line 56, in <module>
app.run(debug = True, port = 80)
File "/home/parth/.local/lib/python3.6/site-packages/flask/app.py", line 990, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 988, in run_simple
s.bind(server_address)
PermissionError: [Errno 13] Permission denied
This is the code
import os, sys
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['GET'])
def verify():
# Webhook verification
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == "hello":
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return "Hello world", 200
if __name__ == "__main__":
app.run(debug = True, port = 80)
Thanks!

You're getting that error because you're using a Privileged Port.
The TCP/IP port numbers below 1024 are special in that normal users
are not allowed to run servers on them.
...
When you run a server as a test from a non-priviliged account, you
will normally test it on other ports, such as 2784, 5000, 8001 or
8080.
Change your port to 5000, for example, and that will fix your problem.

Related

Need help accessing a virtual server using Flask

So for our last coding projects we've set up a web API that runs on local host. But now he has set up a virtual server for us to use along with usernames and passwords to use as well as which ports we are alllowed to use. I have my current code here. On the last line it used to be localhost and the port was 8080 but I changed it to reflect the new server we were given. However, it doesn't work and I couldn't seem to find a solution online. I also have the IP address and it didn't work either. I wasn't sure how to add my username and password to the mix as well as I am sure it is needed to access the server.
from flask_cors import CORS
import os
from flask import Flask, jsonify, make_response, Blueprint
from flask_swagger_ui import get_swaggerui_blueprint
from routes import request_api
import ssl
context = ssl.SSLContext()
context.load_cert_chain('certificate.pem', 'key.pem')
APP = Flask(__name__)
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'
SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={
'app_name': "Kales Flask Project"
}
)
APP.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
APP.register_blueprint(request_api.get_blueprint())
#APP.errorhandler(400)
def handle_400_error(_error):
return make_response(jsonify({'error': 'Misunderstood'}), 400)
#APP.errorhandler(404)
def handle_404_error(_error):
return make_response(jsonify({'error': 'Not found'}), 404)
#APP.errorhandler(401)
def handle_401_error(_error):
return make_response(jsonify({'error': 'Invalid Key Provided'}), 401)
if __name__ == '__main__':
CORS = CORS(APP)
APP.run(host='easel4.cs.utsarr.net', port=int(os.environ.get('PORT', 12145)), ssl_context=context)
Here is the output when I attempt to run this code
C:\Users\kingk\PycharmProjects\AdvanceSoft>python webapi.py
* Serving Flask app "webapi" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "webapi.py", line 44, in <module>
APP.run(host='10.100.201.3', port=12145, ssl_context=context)
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\flask\app.py", line 943, in run
run_simple(host, port, self, **options)
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 1009, in run_simple
inner()
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 962, in inner
fd=fd,
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 805, in make_server
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 698, in __init__
HTTPServer.__init__(self, server_address, handler)
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 452, in __init__
self.server_bind()
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\http\server.py", line 137, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
OSError: [WinError 10049] The requested address is not valid in its context
I assume the host='easel4.cs.utsarr.net' is the problem. The Flask documentation of the run method of the Application object recommends:
host – the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present.

'AttributeError: module '__main__' has no attribute '__package__'

I was trying to build flask-web API. When I am trying to run the app.py code, I have got this error, please refer the code which I have mentioned below. Do I have to install some package to get 'package' into 'main'?
I tried to run in different platforms such jupyter notebook, spyder and Google Colab too, but it didn't work, and getting similar issues.
Here is my app.py code whic is giving error:
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
#app.route('/')
def home():
return render_template('index.html')
#app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
int_features = [int(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)
output = round(prediction[0], 2)
return render_template('index.html', prediction_text='Employee Salary should be $ {}'.format(output))
#app.route('/predict_api',methods=['POST'])
def predict_api():
'''
For direct API calls trought request
'''
data = request.get_json(force=True)
prediction = model.predict([np.array(list(data.values()))])
output = prediction[0]
return jsonify(output)
if __name__ == "__main__":
app.run(debug=True)
Here is the error message I have got:
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
Traceback (most recent call last):
File "<ipython-input-21-3add8626fce0>", line 36, in <module>
app.run(debug=True)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\flask\app.py", line 990, in run
run_simple(host, port, self, **options)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\serving.py", line 1007, in run_simple
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 332, in run_with_reloader
sys.exit(reloader.restart_with_reloader())
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 159, in restart_with_reloader
args = _get_args_for_reloading()
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 76, in _get_args_for_reloading
if __main__.__package__ is None:
AttributeError: module '__main__' has no attribute '__package__'}

Unable to deploy Python Flask application in Google App Engine Flex Environment

I have searched in multiple places and have tried multiple ways to find a solution to this. But nothing was helpful, can you please help me provide the solution. It is getting extremely difficult to host a python flask application in google app engine flexible environment. Python code: "getresource.py"
Here is the link from google to deploy Python Flask application
Here is the simple code:
from flask import Flask, jsonify
from pymysql import connections, ProgrammingError, DatabaseError, MySQLError, DataError
from os import environ
DB_HOST = environ.get("DB_HOST")
USER = environ.get("USER")
PWD = environ.get("PASSWORD")
DATABASE = environ.get("DATABASE")
app = Flask(__name__)
dbconn = connections.Connection(
host=DB_HOST,
port=3306,
user=USER,
password=PWD,
db=DATABASE
)
#app.route("/getResource/<id>", methods=['GET'])
def getresource(id):
result = ()
select_sql = "SELECT `id`, `firstName`, `middleName`, `lastName`, `listOfTechWorkedOn`, `certifications`, `projects`, `applicationWorkLoadTypes` FROM `resource` WHERE `id`=%s"
cursor = dbconn.cursor()
try:
cursor.execute(select_sql, (id))
result = cursor.fetchone()
response = {}
response['id'] = result[0]
response['firstName'] = result[1]
response['middleName'] = result[2]
response['lastName'] = result[3]
response['listOfTechWorkedOn'] = result[4]
response['certifications'] = result[5]
response['projects'] = result[6]
response['applicationWorkLoadTypes'] = result[7]
return jsonify(response)
except ProgrammingError as p:
return
except DatabaseError as d:
return d
except MySQLError as m:
return m
except DataError as de:
return de
dbconn.close()
if __name__ == '__main__':
app.run(host='127.0.0.1',port=8080, debug=True)
Here is the app.yaml file
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT getresource:app
service: getresource
runtime_config:
python_version: 3
manual_scaling:
instances: 1
env_variables:
DB_HOST: "1.2.3.4"
USER: "root"
PASSWORD: "abcdefg"
DATABASE: "abcd"
requirements.txt file
Flask==1.0.2
gunicorn==19.9.0
PyMySQL==0.9.2
I am getting the following error: "gcloud app deploy"
ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment.
I have tried multiple ways, like changing the python code, putting google cloud libraries in the requirements.txt, chaning port, service name etc. But nothing seems to be working.
And surprisingly, I am not getting the error trace in stackdriver logs as well. And Google does not have proper answer it seems (at least from all the googling that i have done)
gcloud version
Google Cloud SDK 222.0.0
bq 2.0.36
core 2018.10.19
gsutil 4.34
**
EDIT:
** Thanks for all the response. I tried all the options, but getting the same error with following debug message. I cannot make anything out of it
Thanks for the response. I tried with all the suggested options, but getting the same error. Following is the debug log, and I cannot make anything out of it.
Updating service [getresource] (this may take several minutes)...failed.
DEBUG: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment.
Traceback (most recent call last):
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 841, in Execute
resources = calliope_command.Run(cli=self, args=args)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 770, in Run
resources = command_instance.Run(args)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\surface\app\deploy.py", line 90, in Run
parallel_build=False)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 620, in RunDeploy
flex_image_build_option=flex_image_build_option)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 422, in Deploy
extra_config_settings)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\appengine_api_client.py", line 207, in DeployService
poller=done_poller)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\operations_util.py", line 315, in WaitForOperation
sleep_ms=retry_interval)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\util\waiter.py", line 254, in WaitFor
sleep_ms, _StatusUpdate)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\util\waiter.py", line 316, in PollUntilDone
sleep_ms=sleep_ms)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\util\retry.py", line 229, in RetryOnResult
if not should_retry(result, state):
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\util\waiter.py", line 310, in _IsNotDone
return not poller.IsDone(operation)
File "C:\Users\M1044921\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\operations_util.py", line 184, in IsDone
encoding.MessageToPyValue(operation.error)))
OperationError: Error Response: [13] An internal error occurred during deployment.
ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment.

How to solve the address issue if I restart an external service inside python with flask?

I am using flask to build a python web service, for example, I set the flask port as 8080 like this:
#app.route('/data', methods=['POST'])
def data_construct():
os.system('sh restart.sh')
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=8080)
and the restart.sh is used for restarting an external service, but after I send a HTTP POST request to /data, the restart is successfully completed, but after a while, I get an error:
Traceback (most recent call last):
File "hello.py", line 87, in <module>
app.run(host='0.0.0.0', port=8080)
File "/home/work/.jumbo/lib/python2.7/site-packages/flask/app.py", line 739, in run
run_simple(host, port, self, **options)
File "/home/work/.jumbo/lib/python2.7/site-packages/werkzeug/serving.py", line 613, in run_simple
test_socket.bind((hostname, port))
File "/home/work/.jumbo/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
the 'restart.sh' is like this (storage is a C++-complied program):
killall storage
nohup ./storage &
and I find the external service is starting using the port 8080 which it is not supposed to do (its original port is still in use), how to solve this problem?

flask run from server 1 using host from server 2

I have a two servers. Is it possible to run the flask from e.g (192.168.1.1) using host = "192.168.1.2"
i got errors
Traceback (most recent call last):
File "app.py", line 38, in <module>
debug=True
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "/usr/local/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address
here is my code. from .e.g 192.168.1.1
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
if __name__ == '__main__':
app.run(
host="192.168.1.2",
port=int("80"),
debug=True
)
This seems to be a misunderstanding on how networking works... You cannot use the IP address of another server as your own, for the same reason you cannot invite people to your neighbor's house and expect them to end up at your door.
If you want to handle web requests on both servers, you are going to need load balancing. Or, a reverse proxy that proxies requests from one server to the other.

Categories