Forums

OSError: [Errno 98] Address already in use

Hello! I am not new to Python, but I am new to Pythonanywhere and somewhat new to programming with flask and dealing with servers/responses etc. I was gonna buy a cheap desktop and load Ubuntu server on it... maybe now I don't have to? :D BTW if someone solves this issue for me, I will become a paying member for sure :D as in tonight :D :D

I have developed a ton of apps for incoming and outgoing calls/texts/emails etc... such as the small example below. They all work on my local machine flawlessly, but the last few nights I have been unsuccessful at deploying them on pythonanywhere. I installed my virtualenv one directory above my "flaskapp" directory... not sure if that matters. I also activate it the way I learned in the past... source bin/activate... Would that cause and issue? It appears to activate just fine. I am using Python3.4 and pip3.4 (edit... redis with 3.5). Also noticed a post similar to this one mentioning Twilio Connect API. I can't seem to find it. It looked as some lines of code were added at the top.

As mentioned before I am new to this web stuff with Python. I usually use NGROK to expose my local address to the public internet. In Twilio, under my webhook where I usually post the the NGROK https url, I put http://myname.pythonanywhere.com/ I am assuming that's correct? All my apps rely heavily on Twilio API.

Any ideas?

from flask import Flask, request, redirect
from twilio.twiml.voice_response import VoiceResponse, Gather, Say
from twilio.rest import Client
import os

app = Flask(__name__)
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)


@app.route("/", methods=['GET', 'POST'])
def hello():
    resp = VoiceResponse()
    resp.say("Hello. Leave a brief message. Speak slowly and clearly.")
    resp.say("Then hang up when finished")
    gather = Gather(input='speech',
                     timeout='10',
                    action="/handle-voice",
                    method="POST")
    gather.say("You may start, now.")
    resp.append(gather)
    return str(resp)

@app.route("/handle-voice", methods=['GET', 'POST'])
def handle_voice():
    resp = VoiceResponse()
    transcription = request.values.get('SpeechResult', None)
    from_number = request.values.get('From', None)
    to_number = request.values.get('To', None)
    confidence = request.values.get('Confidence', None)
    first_message = "Thank you for calling. Your transcribed message is: \n"
    first_message += "<" + transcription + ">"
    first_message += "\nProjected confidence level:\n" + confidence + ".\n"
    client.messages.create(to=from_number, from_=to_number, body=first_message)
    second_message = "You're transcription in binary:\n"
    for char in second_message:
         second_message += bin(ord(char)) + '\n'
    client.messages.create(to=from_number, from_=to_number, body=second_message)
    return str(resp)


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

Please indent or remove this line: app.run(host='0.0.0.0', debug=True) Then reload your webapp. It should work then! Look at "Do not use app.run" https://help.pythonanywhere.com/pages/Flask/ or also https://help.pythonanywhere.com/pages/Flask504Error/

Reason? It is because Flask tries to run it's own web server when Pythonanywhere already has one implemented in the webapp. Just relax and let PA handle the server side.

Wow that was fast! Ok let me try it. Oh that was just a copy/paste error on my part

Ah still no luck... I edited the WSGI file after deleting and reinstalling the webapp:

path = '/home/colleyloyejames/mysite/'
if path not in sys.path:
   sys.path.append(path)

from flask_app import app as application

I also did the virtualenv as suggested in the article... still getting this output

 (virtualenv) 03:47 ~/mysite $ python3.4 flask_app.py 
Traceback (most recent call last):
  File "flask_app.py", line 44, in <module>
     app.run()
  File "/home/colleyloyejames/.virtualenvs/virtualenv/lib/python3.4/site-packages/flask/app.py", line 841, in run
    run_simple(host, port, self, **options)
  File "/home/colleyloyejames/.virtualenvs/virtualenv/lib/python3.4/site-packages/werkzeug/serving.py", line 739, in run_simple
    inner()
   File "/home/colleyloyejames/.virtualenvs/virtualenv/lib/python3.4/site-packages/werkzeug/serving.py", line 699, in inner
     fd=fd)
  File "/home/colleyloyejames/.virtualenvs/virtualenv/lib/python3.4/site-packages/werkzeug/serving.py", line 593, in make_server
    passthrough_errors, ssl_context, fd=fd)
   File "/home/colleyloyejames/.virtualenvs/virtualenv/lib/python3.4/site-packages/werkzeug/serving.py", line 504, in __init__
    HTTPServer.__init__(self, (host, int(port)), handler)
  File "/usr/lib/python3.4/socketserver.py", line 430, in __init__
    self.server_bind()
  File "/usr/lib/python3.4/http/server.py", line 133, in server_bind
    socketserver.TCPServer.server_bind(self)
  File "/usr/lib/python3.4/socketserver.py", line 444, in server_bind
    self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use

and in my script:

if name == 'main': app.run()

as that is what is in the link you sent. If I delete app.run() I get a parsing error

OH I SEE So You are not supposed to run your flask_app.py directly from the console. There is no portforwarding going on in the console. You have to create a webapp configuration (which i think you did), hit the big green reload button, and your website is running! Your website should be located over here if properly setup. http://colleyloyejames.pythonanywhere.com/

Just make sure your wsgi file path = '/home/colleyloyejames/mysite/' points to your flask app location. At this moment, the stuff inside your /mysite/ folder is serving your website.

Oh hahahahah ok let me try that.

So basically, the idea is that you want to set up your wsgi so it can point to your flask app (the path variable) and have it import your app variable inside your flask app (the from flask_app import app as application line)

The webapp in Pythonanywhere will look at your wsgi configuration and follow the code to run your webapp.

To break down the import line, it basically states...

from the flask_app file inside your path folder...

look for references of app inside the flask_app.py

and rename it to application (because uwsgi needs the variable application otherwise it wont work)

Ok I think I got it. I also watched a youtube video. Unfortunately it's giving me this now...

ImportError: No module named 'twilio.twiml.voice_response'; 'twilio.twiml' is not a package

I made sure the latest Twilio and Flask were installed? That seems like an error I would get if my virtualenv wasn't activated

Have you set up virtual env in your webapp? Go to the webapps tab and make sure your virtual env is set properly.

I followed the instructions here for my virtualenvs https://help.pythonanywhere.com/pages/Virtualenvs/ and my configuration looks like /home/EndenDragon/.virtualenvs/titanembeds in the webapp tab.

yup I had already tried... all I had to do was enter the name, press enter, and it found it automatically. I am using the wrapper... I now call workon virtualenv to activate it. I really am stumped.. been searching online but can't find much.

Saw a post that recommended trying to run the wsgi file itself to trouble shoot.

$ python3.5 -i /var/www/www_..... wsgi.py

this gives the same error as when I press the run button:

ImportError: No module named 'twilio.twiml.voice_response'; 'twilio.twiml' is not a package

Unfortunately it definitely is a package hahahah I double checked virtualenv and it looks fine. BTW I deleted the old webapp hours ago, and redid everything in 3.5.

Again this script works fine locally

BTW I really appreciate you trying to help!

Do you have the twilio package installed? Try going back into your virtual env with workon command in a console and try importing twilo from twilio.twiml.voice_response import VoiceResponse. If the error occurs, then you may have to install twilio inside your virtualenv

EDIT: Pythonanywhere's batteries included has an old version of twilio (5.4.0). As we speak, it's 6.3.0. I looked at twilio's github repo and their codebase changed alot between v5 and v6. voice_response is not included in v5. I would agree that you must install twilio in your virtualenv with pip to get the latest version.

Well I activated virtualenv, then installed flask and twilio in one shot with a requirements.txt

Flask>=0.12 twilio~=6.0.0

(virtualenv) 07:23 ~/virtualenv $ pip3.5 install twilio
Requirement already satisfied: twilio in ./lib/python3.5/site-packages                                                                                                                                     
Requirement already satisfied: pysocks in ./lib/python3.5/site-packages (from twilio)                                                                                                                      
Requirement already satisfied: requests>=2.0.0 in ./lib/python3.5/site-packages (from twilio)                                                                                                              
Requirement already satisfied: pytz in ./lib/python3.5/site-packages (from twilio)                                                                                                                         
Requirement already satisfied: PyJWT>=1.4.2 in ./lib/python3.5/site-packages (from twilio)                                                                                                                 
Requirement already satisfied: six in ./lib/python3.5/site-packages (from twilio)                                                                                                                          
Requirement already satisfied: idna<2.6,>=2.5 in ./lib/python3.5/site-packages (from requests>=2.0.0->twilio)                                                                                              
Requirement already satisfied: urllib3<1.22,>=1.21.1 in ./lib/python3.5/site-packages (from         requests>=2.0.0->twilio)                                                                                       
 Requirement already satisfied: certifi>=2017.4.17 in ./lib/python3.5/site-packages (from requests>=2.0.0->twilio)                                                                                          
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in ./lib/python3.5/site-packages (from requests>=2.0.0->twilio)

If I go into a bash console while virtualenv is activated, enter the python3.5 interpreter, oddly enough it works:

(virtualenv) 07:26 ~/virtualenv $ python3.5                                                                                                                                                                
Python 3.5.2 (default, Jul 17 2016, 00:00:00)                                                                                                                                                              
[GCC 4.8.4] on linux                                                                                                                                                                                       
Type "help", "copyright", "credits" or "license" for more information.                                                                                                                                     
>>> from twilio.twiml.voice_response import VoiceResponse, Gather, Say                                                                                                                                      
>>>

I gotta go to bed ... 330 am here... well I'll check back tomorrow. Thanks again

Alright, rest well. But you're saying that the webapp doesnt import correctly, just the console?

Yeah I think? It seems like it's not activating the virtualenv. But on the "Web" tab the path to the virtualenv is highlighted green and looks ok... I am able to start a console from it. Losing sleep over it hahaha. I'm gonna start over from the beginning tomorrow.

Things to check: 1. Are you reloading your web app when you change the code/install modules? 2. Do the versions of Python agree between your web app and your virtualenv? 3. Is the import that is giving your the error the same as the one you're testing in the console?

Hi Glenn let me get back to you... gonna try again at some point today. I typically use 3.5 for everything... while creating my webapp, creating my virtualenv, and installation of flask and twilio (ie pip3.5). The first time around I used 3.4. I'll get back to you though thanks

Yeah still no luck.. Just re-did everything. I took a screenshot of every step though. Is it ok to send in an email to you?

Hey Glenn I just sent an email with some screenshots to the support email address! Maybe there's something I am missing?

Solved offline

Am getting this error please help . Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Have you checked the error log? There's a link on the "Web" page, and the most recent error will be at the bottom.

anyone??

What is the exact problem that you're having?

OSError: [Errno 98] Address already in use. I need to kill the process. Please help me in this issue

Could you provide more context? Sent it to support@pythonanywhere.com if you do not want to share it on public forums.

Has anyone got answer to this Question . Cause i am facing the same issue

@Arthavruksha -- could you provide some more details? If you prefer, you may contact us at support@pythonanywhere.com, as @fjl already suggested above.

Here's the link where i have discussed the issue in-depth - https://www.pythonanywhere.com/forums/topic/31352/#id_post_103354

All right, it looks like the issue is related to the internet restrictions on the free account.