I'm making a chat server on Django and atm trying to implement websockets.
It works fine locally but whenever I launch it on Heroku, websocket is unreachable.
Here's my client script:
var loc = window.location
var ws_start = 'ws://'
if (loc.protocol == 'https:'){
ws_start = 'wss://'
}
var endpoint = ws_start + loc.host + loc.pathname
var socket = new WebSocket(endpoint)
Full error code:
WebSocket connection to 'wss://my-app.herokuapp.com/chat' failed: Error during WebSocket handshake: Unexpected response code: 500
I've seen a variety of similar questions already, and they are either left unanswered or delve into dealing with SSL certificate. There's one answer that would potentially save me (and other folks) alot of frustration if anyone was to confirm it's true. It's quite old and there's no feedback after it was posted: https://stackoverflow.com/a/45173822/7446564.
Thanks to Heroku logs, I was able to get the actual error message:
Django daphne asgi: Django can only handle ASGI/HTTP connections, not websocket
This answer helped me fix it: https://stackoverflow.com/a/59909118/7446564
So in conclusion: if you have an error launching websockets on Django, make sure your .asgi file is properly set up. I'll also attach my Procfile below since setting it up first time was also a little journey and I hope it might be helpful as well:
web: daphne my-app.asgi:application --port $PORT --bind 0.0.0.0 -v2
Related
When I execute the line from inside a request:
page = requests.get("http://localhost:5000/some/page/")
with DEBUG logging turned on, the output is:
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): localhost:5000
send: 'GET /some/page/ HTTP/1.1\r\nHost: localhost:5000\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.22.0\r\n\r\n'
and execution will not progress past this point. Am I missing a step somewhere?
Update:
This is happening for requests that themselves contain a requests.get(). So, I think flask is trying to do two different things at once and the dev server is unable to handle that. That also explains why this seems to work on my staging server.
I've tried running Flask with threaded=True, but that didn't make a difference. Any ideas on a fix for the purposes of local dev and testing?
Update2:
Wrapping in with app.test_client() as c: and using c.get() works for localhost, but fails in staging
I don't want to use getUpdates method to retrieve updates from Telegram, but a webhook instead.
Error from getWebhookInfo is:
has_custom_certificate: false,
pending_update_count: 20,
last_error_date: 1591888018,
last_error_message: "SSL error {error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed}"
My code is:
from flask import Flask
from flask import request
from flask import Response
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def bot():
if request.method == 'POST':
return Response('Ok', status=200)
else:
return f'--- GET request ----'
if __name__ == "__main__":
app.run(host='0.0.0.0', port='8443', debug=True, ssl_context=('./contract.crt', '.private.key'))
When I hit https://www.mydomain.ext:8443/ I can see GET requests coming but not POST ones when I write something on my telegram-bot chat
Also that's how I set a webhook for telegram as follow:
https://api.telegram.org/botNUMBER:TELEGRAM_KEY/setWebhook?url=https://www.mydomain.ext:8443
result:
{
ok: true,
result: true,
description: "Webhook was set"
}
Any suggestion or something wrong I've done?
https://core.telegram.org/bots/api#setwebhook
I'm wondering if the problem it's caused because I'm using 0.0.0.0, the reason it's that if I use 127.0.0.0 the url/www.mydomain.ext cannot be reached
Update
ca_certitificate = {'certificate': open('./folder/ca.ca-bundle', 'rb')}
r = requests.post(url, files=ca_certitificate)
print(r.text)
that print gives me:
{
"ok": false,
"error_code": 400,
"description": "Bad Request: bad webhook: Failed to set custom certificate file"
}
I deployed a Telegram chatbot without Flask a while ago.
I remember that the POST and GET requests required /getUpdates and /sendMessage added to the bot url. Maybe it will help.
Telegram bots only works with full chained certificates. And the error in your getWebHookInfo:
"last_error_message":"SSL error {337047686, error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed}"
Is Telegram saying that it needs the whole certificate chain (it's also called CA Bundle or full chained certificate). as answered on the question.
If you validate your certificate using the SSLlabs you will see that your domain have chain issues:
https://www.ssllabs.com/ssltest/analyze.html?d=www.vallotta-party-bot.com&hideResults=on
To solve this need you need to set the CA Certificate. In this way, you need to find the CA certificate file with your CA provider.
Also, the best option in production sites is to use gunicorn instead of Flask.
If you are using gunicorn, you can do this with command line arguments:
$ gunicorn --certfile cert.pem --keyfile key.pem --ca_certs cert.ca-bundle -b 0.0.0.0:443 hello:app
Or create a gunicorn.py with the following content:
import multiprocessing
bind = "0.0.0.0:443"
workers = multiprocessing.cpu_count() * 2 + 1
timeout = 120
certfile = "cert/certfile.crt"
keyfile = "cert/service-key.pem"
ca_certs = "cert/cert.ca-bundle"
loglevel = 'info'
and run as follows:
gunicorn --config=gunicorn.py hello:app
If you use Nginx as a reverse proxy, then you can configure the certificate with Nginx, and then Nginx can "terminate" the encrypted connection, meaning that it will accept encrypted connections from the outside, but then use regular unencrypted connections to talk to your Flask backend. This is a very useful setup, as it frees your application from having to deal with certificates and encryption. The configuration items for Nginx are as follows:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# ...
}
Another important item you need to consider is how are clients that connect through regular HTTP going to be handled. The best solution, in my opinion, is to respond to unencrypted requests with a redirect to the same URL but on HTTPS. For a Flask application, you can achieve that using the Flask-SSLify extension. With Nginx, you can include another server block in your configuration:
server {
listen 80;
server_name example.com;
location / {
return 301 https://$host$request_uri;
}
}
A good tutorial of how setup your application with https can be found here: Running Your Flask Application Over HTTPS
I had similar case. I was developing bot on localhost (yet without SSL) and tunneled it to web through ngrok. In beginning all was OK, but once I found no POST-requests are coming. It turned out time of tunneling expired. I laughed and restarted tunneling. But requests weren't coming. It turned out, I forgot to change address of webhook (it switches every ngrok session). Don't repeat my errors.
I have deployed my own apprtc server with collider & turn server configured in Google App engine locally with virtualbox. Everything is working properly but I want to use this apprtc server in my another project that is in anoter IP. So, Apprtc IP and my project IP is different. Now, when I included apprtc.debug.js & appwindow.js files to my project it cannot initialize loadingParams and says this error message "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<IP OF APPRTC>:8080/params. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)".
However, entering http://<IP OF APPRTC>:8080/params in the browser gives me correct response but not in the project called in appwindow.js .After a bit of googling I added below lines in sendUrlRequest function :
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
Now it says "CORS request did not succeed".
How can I make it work? Do I have to enable cors in server side also, if so where and how to do that? Please help me, I'm totally lost here...
I'm trying to get Flask-Mail setup on in Flexible ENV on Google App Engine. Flask-Mail works on my localhost using the credentials for a domain I am trying to use to send the mail. However, when using it on GAE through my API it returns a 502 error, however it shows no error messages in the logs or console. Going through the documentation for GAE Flexible it doesn't mention anything about NOT being able to use it, however it doesn't show how one would setup Flask-Mail either.
I have this..
mail = Mail()
print('1') // We Get here
msg = Message("Hello",
sender="me#mydomain.com",
recipients=["me#mydomain.com"])
print('2') // We get here
msg.body = 'Testing'
print('3') // We get here
mail.send(msg)
print('4') // This never gets call because I timeout on a 502 before this
I can tell I am not getting any fatal errors because the app stays working. However this fails with the 502. I have tried adding my email to the list of authorized senders but it doesn't seem to have helped.
I would appreciate any feedback. If I forced to use a 3rd party service to send mail it may cause me to move the project off of GAE.
As Ivan posted on his comment, to send email from a GAE app you need to use a mail service. Right now there are 3 options for apps on a flexible environment: Mailgun, MailJet and SendGrid. Choose the one you see better for your app.
After setting up an account on the mail service you have chosen, you have to prepare your code by integrating the parts related to the mail service.
These tutorials should help you establish the mail service for your app:
Mailgun
MailJet
SendGrid
I've had the same error but on a virtual machine on the internet ( linode service ) and it turned out that it has some thing to do with rDNS and some domain name config that you have to set up for your Ip address to get things working correctly , check this
https://www.linode.com/community/questions/19082/i-just-created-my-first-linode-and-i-cant-send-emails-why
I have my web app API running.
If I go to http://127.0.0.1:5000/ via any browser I get the right response.
If I use the Advanced REST Client Chrome app and send a GET request to my app at that address I get the right response.
However this gives me a 503:
import requests
response = requests.get('http://127.0.0.1:5000/')
I read to try this for some reason:
s = requests.Session()
response = s.get('http://127.0.0.1:5000/')
But I still get a 503 response.
Other things I've tried: Not prefixing with http://, not using a port in the URL, running on a different port, trying a different API call like Post, etc.
Thanks.
Is http://127.0.0.1:5000/ your localhost? If so, try 'http://localhost:5000' instead
Just in case someone is struggling with this as well, what finally worked was running the application on my local network ip.
I.e., I just opened up the web app and changed the app.run(debug=True) line to app.run(host="my.ip.address", debug = True).
I'm guessing the requests library perhaps was trying to protect me from a localhost attack? Or our corporate proxy or firewall was preventing communication from unknown apps to the 127 address. I had set NO_PROXY to include the 127.0.0.1 address, so I don't think that was the problem. In the end I'm not really sure why it is working now, but I'm glad that it is.