Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am trying to build a website where a user can enter text, which will be picked up via javascript, and sent to a python function where it will be posted to twitter. For the time being, the python function is being stored locally, along with the rest of the site. However, my AJAX isn't too great and I'm having a few issues.

I have written AJAX code which sends a POST request to the python function with the tweet, and the response is the entire python script. No connection is made to the socket my script is listening to. Below is the AJAX function and the python script. Any ideas what's going on?

Thanks in advance for any help!

$(function(){
    $('#PostTweet').on('click', function(e) {

    var tweet = document.getElementById("theTweet").value;
    var len = tweet.length;

    if(len > 140){
        window.alert("Tweet too long. Please remove some characters");
    }else{

        callPython(tweet);
    }     

    });

});

function callPython(tweet){
 window.alert("sending");
 $.ajax({
 type: "POST",
 url: "tweet.py",
 data: tweet,
 success: function(response){
    window.alert(response);
  }
 })
}

And the Python Script:

from OAuthSettings import settings
import twitter
from socket import *

consumer_key = settings['consumer_key']
consumer_secret = settings['consumer_secret']
access_token_key = settings['access_token_key']
access_token_secret = settings['access_token_secret']

s = socket()
s.bind(('', 9999))
s.listen(4)
(ns, na) = s.accept()

def PostToTwits(data):    
   try:
     api = twitter.Api(
     consumer_key = consumer_key,
     consumer_secret = consumer_secret,
     access_token_key = access_token_key,
     access_token_secret = access_token_secret)

     api.PostUpdate(data)
     makeConnection(s)
   except twitter.TwitterError:
     print 'Post Unsuccessful. Error Occurred'


def makeConnection(s):
    while True:

       print "connected with: " + str(na)
       try:
           data = ns.recv(4096)
           print data
           PostToTwits(data)
       except:
           ns.close()
           s.close()
           break

makeConnection(s)
share|improve this question

Your problem is that you are working with pure sockets which know nothing about HTTP protocol. Take a look at Flask or Bottle web micro frameworks to see how to turn python script or function into web endpoint.

share|improve this answer
    
Thanks a lot! That would seem to make sense, I'll do some research! Out of curiosity, do you know if this sort of thing is possible at all without the micro frameworks? – CHByte Aug 27 '15 at 11:54
    
Of course it's possible but just as @RobertMoskal said in his answer it would get tedious and with so many libraries out there I see no reason for doing this, besides educational. If you don't want to use framework for this, check out e.g. wsgiref or BaseHTTPServer which are part of python standard library. – beezz Aug 27 '15 at 12:01

you need a webserver so that your can make request via web browser.

you can web framework like flask or django or you can use webpy.

A simple example using webpy from their website

import web

urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:        
    def GET(self, name):
        if not name: 
            name = 'World'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app.run()

then you call url(your python function) from javascript.

share|improve this answer

You can totally write a simple web server using sockets, and indeed you've done so. But this approach will quickly get tedious for anything beyond a simple exercise.

For example, your code is restricted to handling a single request handler, which goes to the heart of your problem.

The url on the post request is wrong. In your setup there is no notion of a url "tweet.py". That url would actually work if you were also serving the web page where the jquery lives from the same server (but you can't be).

You have to post to "http://localhost:9999" and you can have any path you want after:"http://localhost:9999/foo", "http://localhost:9999/boo". Just make sure you run the python script from the command line first, so the server is listening.

Also the difference between a get and a post request is part of the HTTP protocol which your simple server doesn't know anything about. This mainly means that it doesn't matter what verb you use on the ajax request. Your server listens for all HTTP verb types.

Lastly, I'm not seeing any data being returned to the client. You need to do something like ns.sendall("Some response"). Tutorials for building a simple http server abound and show different ways of sending responses.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.