I'm trying to run a simple Flask API, but it's not working as expected. I'm not very experienced in Python, so found the error and solve it have been very challenging. I would appreciate a lot if someone could help.
The system's settings are:
And these are the requirements:
$ pip freeze
ansimarkup==1.4.0
asn1crypto==0.24.0
better-exceptions-fork==0.2.1.post6
certifi==2019.3.9
cffi==1.12.3
chardet==3.0.4
Click==7.0
colorama==0.4.1
cryptography==2.7
Flask==1.0.3
idna==2.8
itsdangerous==1.1.0
Jinja2==2.10.1
loguru==0.2.5
MarkupSafe==1.1.1
pycparser==2.19
Pygments==2.4.2
pyOpenSSL==19.0.0
PySocks==1.7.0
requests==2.22.0
six==1.12.0
urllib3==1.24.2
Werkzeug==0.15.4
My project structure is like this:
├── statsapi
│ ├── data_store.py
├── app.py
├── client.py
├── requirements.txt
Here is the app.py code:
#!/usr/bin/env python
from flask import Flask, request, jsonify
from loguru import logger
from statsapi import data_store
app = Flask(__name__)
# Creating an endpoint
@app.route("/data", methods=["POST"])
def save_data():
# setting log for this action
logger.info(f"Saving data...")
# transform content requisition to json
content = request.get_json()
# save in a module just the "data" field
# The uuid of the data
uuid = data_store.save(content["data"])
# set log for las action
logger.info(f"Data saved with UUID `{uuid}` successfully")
# define information to be returned
return jsonify({"status": "success",
"message": "data saved successfully",
"uuid": uuid})
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
The data_store.py code:
#!/usr/bin/env python
from uuid import uuid4
# Create a dictionary to keep things in memory
_in_memory_storage = dict()
# Save received data in memory giving an uuid
def save(data):
data_uuid = uuid4()
_in_memory_storage[data_uuid] = data
return data_uuid
And the client.py code:
#!/usr/bin/env python
import requests
def send(data):
response = requests.post("http://localhost:5000/data", json={"data": data})
print(response.json())
def main():
send([1, 2, 3, 4])
if __name__ == "__main__":
main()
The client.py should send some data to API, but when called it returns this long error message:
$ python client.py
Traceback (most recent call last):
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/connection.py", line 159, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/util/connection.py", line 80, in create_connection
raise err
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/util/connection.py", line 70, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/http/client.py", line 1229, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/http/client.py", line 1275, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/http/client.py", line 1224, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/http/client.py", line 1016, in _send_output
self.send(msg)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/http/client.py", line 956, in send
self.connect()
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/connection.py", line 181, in connect
conn = self._new_conn()
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fd0c7a26a58>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/urllib3/util/retry.py", line 399, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /data (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd0c7a26a58>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "client.py", line 17, in <module>
main()
File "client.py", line 13, in main
send([1, 2, 3, 4])
File "client.py", line 7, in send
response = requests.post("http://localhost:5000/data", json={"data": data})
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/requests/api.py", line 116, in post
return request('post', url, data=data, json=json, **kwargs)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/home/bruno/anaconda3/envs/statsapi/lib/python3.7/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /data (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd0c7a26a58>: Failed to establish a new connection: [Errno 111] Connection refused'))
As I said, I'm far away from to be a python expert, so I will be many thankful for any help.
Might not exactly relate to the question, but it might help someone facing similar issue.
I had similar issue, but in my case it was because of docker containers. When container #1 is connecting to container #2 using requests api it was failing as both the containers are not in a single network.
So I modified my docker-compose file to
networks:
default:
external: true
name: <network_name>
Make sure to create the docker network in advance and modify the host to docker service name of the container #2 while connecting using requests.
So use http://<docker_service_name>:8000/api
instead of http://127.0.0.1:8000/api
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With