python dropbox upload error - python

class GenericUploader(object):
def __init__(self, data, fname):
"""data is the string we want to upload"""
self.log = logging.getLogger(type(self).__name__)
self.data = data
self.data.seek(0)
self.fname = fname
def upload(self):
"""Should return true or false"""
raise NotImplementedError
class SshUploader(GenericUploader):
def __init__(self, data, fname, user, host):
GenericUploader.__init__(self, data, fname)
self.log.debug('Initializing SshUploader')
self.user = user
self.host = host
def upload(self):
import subprocess
proc = subprocess.Popen(['ssh', self.user + '#' + self.host,
'cat > %s' % self.fname],
stdin=subprocess.PIPE)
proc.communicate(self.data.getvalue())
if proc.returncode != 0:
self.log.critical('Problem writing to remote server %s#%s: %d',
self.user, self.hos, proc.returncode)
return False
else:
self.log.debug('Uploaded to ssh server %s#%s', self.user, self.host)
return True
class FtpUploader(GenericUploader):
def __init__(self, data, fname, user, host, passwd):
GenericUploader.__init__(self, data, fname)
self.log.debug('Initializing FtpUploader')
self.user = user
self.host = host
self.passwd = passwd
def upload(self):
import ftplib
try:
session = ftplib.FTP(self.host, self.user, self.passwd)
session.storbinary('STOR %s' % self.fname, self.data)
session.quit()
except:
self.log.exception('Ftp upload failed')
return False
else:
self.log.debug('Uploaded to ftp server %s#%s', self.user, self.host)
return True
class DropBoxUploader(GenericUploader):
def __init__(self, data, fname, access_token):
GenericUploader.__init__(self, data, fname)
self.access_token = access_token
def upload(self):
import config
try:
import dropbox
except ImportError:
self.log.critical('dropbox module is required![pip install dropbox]')
return False
try:
client = dropbox.client.DropboxClient(self.access_token)
# print 'linked account: ', client.account_info()
response = client.put_file(self.fname, self.data)
except dropbox.rest.ErrorResponse, e:
self.log.exception('Exception uploading to dropbox: %s', str(e))
return False
except Exception:
self.log.exception('Unknown exception while uploading to dropbox')
return False
else:
self.log.debug('Uploaded to dropbox of: %s', str(client.account_info()))
return True
The above code works perfect for SshUploader & FtpUploader.
The DropBoxUploader throws the exception:
Traceback (most recent call last):
2¦ File "/media/sf_aptata/ManhattanApi/insertors/uploaders.py", line 96, in upload
response = client.put_file(self.fname, self.data)
File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/client.py", line 321, in put_file
return self.rest_client.PUT(url, file_obj, headers)
File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/rest.py", line 264, in PUT
return cls.IMPL.PUT(*n, **kw)
File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/rest.py", line 210, in PUT
return self.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/rest.py", line 180, in request
r = conn.getresponse()
File "/usr/lib/python2.7/httplib.py", line 1034, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 407, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 371, in _read_status
raise BadStatusLine(line)
BadStatusLine: ''
self.data is a file like object ( http://docs.python.org/2/library/io.html#io.BytesIO )
Tested on :
linux, python 2.7.3, pip install dropbox [https://www.dropbox.com/developers/core/sdks/python]
any ideas?

Related

Paho connection problem - Mosquitto: A network protocol error occurred when communicating with the broker

I run mosquitto (docker image - on external server)
After some period of time, my mosquitto does not work and show me this error (I do not know why)
A network protocol error occurred when communicating with the broker.
When this mosquitto error occures and I try connect/publish, (python) paho.mqtt throws me this:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
2913, in _thread_main
self.loop_forever(retry_first_connection=True)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
1578, in loop_forever
rc = self.loop(timeout, max_packets)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
1072, in loop
rc = self.loop_read(max_packets)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
1374, in loop_read
rc = self._packet_read()
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
2071, in _packet_read
rc = self._packet_handle()
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
2560, in _packet_handle
return self._handle_publish()
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
2728, in _handle_publish
(topic, packet) = struct.unpack(pack_format, packet) struct.error: bad char in struct format
It looks like my paho.mqtt.client is still connected but even if I restart mosquitto and I use mosquitto_sub (mosquitto error it's gone) I still do not see messages from my program. I need to restart program but it is not satisfying solution.
Could you tell me please, why mosquitto shows me this error and/or how can I catch (python) paho.mqtt socket.error (It's possible?)
I think that this part of code should be enought :)
mqtt_client.py
class MQttClient:
client = None
connected_flag = False
loop_is_working_flag = False
broker_is_online_flag = True
subscribe_command_channel_flag = True
mosquitto_ip = None
def __init__(self, config):
self.config = config
self.logger = Logger(config, self)
def connect(self, ip_address='127.0.0.1', port=1883, keepalive=4):
self.mosquitto_ip = ip_address
self.client = mqtt.Client(self.config.get(REQUIRE_INI_SECTION, DEVICE_ID_INI_PARAMETER), clean_session=False)
self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
try:
self.client.connect(ip_address, port, keepalive=keepalive)
self.client.loop_start()
self.wait_for_connect()
self.loop_is_working_flag = True
except (OSError, ConnectionRefusedError):
self.logger.error(CAN_NOT_CONNECT_WITH_IP_ADDRESS_ERROR.format(ip_address), send_to_mosquitto=False)
def publish_message(self, message, topic, retain=False):
return self.client.publish(self.config.get(REQUIRE_INI_SECTION, BUILDING_NAME_INI_PARAMETER)
+ '/' + topic + '/' +
self.config.get(REQUIRE_INI_SECTION, DEVICE_ID_INI_PARAMETER), message, qos=1,
retain=retain)
def on_connect(self, client, userdata, flags, rc):
if rc is 0:
self.connected_flag = True
self.logger.info(CONNECTED_TO_THE_MOSQUITO_INFO.format(self.mosquitto_ip), send_to_mosquitto=True)
def on_disconnect(self, client, userdata, rc):
if rc is not 0:
self.connected_flag = False
self.logger.error(DISCONNECTED_FROM_THE_MOSQUITO_ERROR.format(
self.mosquitto_ip, str(rc)), send_to_mosquitto=True)
def wait_for_connect(self):
while not self.connected_flag:
pass
...
And usage:
controller.py
class Controller:
def __init__(self):
self.config = configparser.ConfigParser()
self.config.read(CONFIG_FILE_PATH)
self.client = MQttClient(self.config)
self.__connect_to_mosquitto()
def __connect_to_mosquitto(self):
if Network.host_is_available(self.config.get(NETWORK_INI_SECTION, BROKER_IP_INI_PARAMETER)):
if not self.client.loop_is_working_flag:
self.client.connect(ip_address=self.config.get(NETWORK_INI_SECTION, BROKER_IP_INI_PARAMETER))
time.sleep(0.2)
self.client.publish_message(self.json_parser.get_json_welcome_data(), MOSQUITTO_TOPIC_WELCOME_DATA)
else:
self.logger.error(NO_CONNECTION_WITH_BROKER_ERROR, send_to_mosquitto=False)
Network.restart_network_interface_if_there_is_no_connection(
self.config.get(NETWORK_INI_SECTION, ROUTER_IP_INI_PARAMETER))
...
def execute(self):
while self.client.connected_flag and self.client.broker_is_online_flag:
...
if self.client.publish_message(data, MOSQUITTO_TOPIC_DATA)[0] is not 0:
...
self.logger.error(CAN_NOT_SEND_DATA_TO_MOSQUITTO_ERROR)
break
I checked and this method returns 0 (success). But I do not get messages on mosquitto_sub
self.client.publish_message(data, MOSQUITTO_TOPIC_DATA)[0]

exception raised by tornado

I wrote a simple http server with Tornado, but sometimes it raise exception below, self.session.response runs in a threadpool.
code of server:
class AuToServer(object):
module_path = os.path.split(os.path.realpath(__file__))[0] + '/../module/'
def __init__(self, prefix=DEFAULT_PREFIX, work_root=module_path, module=[], **kwargs):
self._prefix = prefix
self._thread_pool = ExecutorDelegate(20)
self._module_manager = ModuleManager(work_root)
self.initilize(module, kwargs)
def initilize(self, modules, kwargs):
self._module_manager.set_args(kwargs)
if not self._module_manager.prepare(modules):
print "initilize module fail. [%s]" % (str(modules))
raise AppInitError("initilize %s fail" % (modules))
def __call__(self, request): # request handler
session = Session(request)
if not session.parse(self._prefix):
print "parse query fail. [%s]" % (session.query)
session.response("url parse fail [%s]\n" % session.query)
return
self._thread_pool.submit(WorkerHander(self._module_manager, session))
def start(self, port=8880):
http_server = tornado.httpserver.HTTPServer(self, max_header_size=128*1024)
http_server.listen(port)
tornado.ioloop.IOLoop.instance().start()
code of WorkerHander:
class WorkerHander(BaseExecutor):
def __init__(self, module_manage, session):
self.module_manage = module_manage
self.session = session
super(WorkerHander, self).__init__(self)
def run(self):
method = self.session.get_command()
if not method:
self.session.response("invalid url [%s]\n" % (self.session.query))
return
context = self.module_manage.run(method, self.session)
try:
if context:
self.session.response(context) # raise exception
else:
self.session.response("None\n")
except Exception, error:
Logger.warning("session response fail. [%s][%s]" % (self.session.query, traceback.format_exc()))
code of session.response
def response(self, context):
if not self.request:
return False
if isinstance(context, unicode):
context = context.encode("utf8")
self.request.write(utf8("%s %d\r\n\r\n%s" % (
HTTP_HEADER,
len(context),
context)))
Logger.debug("QUERY:[cmd:%s][%s] [%s] [%s]" % (
self.command,
time.time() - self.begin_time,
self.request.remote_ip,
self.query))
self.request.finish()
return True
exception:
2016-02-29 16:29:26,852 WARNING: server.py:run:94: session response fail. [/auto?start_timestamp=1456730772&_cmd=get_index_info][Traceback (most recent call last):
File "/home/admin/autobots/lib/python2.7/site-packages/autobase-0.0.1-py2.7.egg/autobase/service/server.py", line 90, in run
self.session.response(context)
File "/home/admin/autobots/lib/python2.7/site-packages/autobase-0.0.1-py2.7.egg/autobase/service/session.py", line 43, in response
self.request.finish()
File "/home/admin/autobots/lib/python2.7/site-packages/tornado-4.2-py2.7-linux-x86_64.egg/tornado/httputil.py", line 407, in finish
self.connection.finish()
File "/home/admin/autobots/lib/python2.7/site-packages/tornado-4.2-py2.7-linux-x86_64.egg/tornado/http1connection.py", line 459, in finish
self._pending_write.add_done_callback(self._finish_request)
File "/home/admin/autobots/lib/python2.7/site-packages/tornado-4.2-py2.7-linux-x86_64.egg/tornado/concurrent.py", line 243, in add_done_callback
fn(self)
File "/home/admin/autobots/lib/python2.7/site-packages/tornado-4.2-py2.7-linux-x86_64.egg/tornado/http1connection.py", line 491, in _finish_request
self.close()
File "/home/admin/autobots/lib/python2.7/site-packages/tornado-4.2-py2.7-linux-x86_64.egg/tornado/http1connection.py", line 297, in close
self.stream.close()
File "/home/admin/autobots/lib/python2.7/site-packages/tornado-4.2-py2.7-linux-x86_64.egg/tornado/iostream.py", line 427, in close
self.close_fd()
File "/home/admin/autobots/lib/python2.7/site-packages/tornado-4.2-py2.7-linux-x86_64.egg/tornado/iostream.py", line 995, in close_fd
self.socket.close()
AttributeError: 'NoneType' object has no attribute 'close'
]
Do I use Tornado in a wrong way? ask for help. thanks~
Tornado is not thread-safe by design. You can use a thread pool to do your own work, but you must call all Tornado methods (including in this case self.request.write and self.request.finish) from the IOLoop thread.

Getting results from query with alchimia library

Im trying to use alchimia for get asynchronous API for DB. Trying to make a simple request to DB, like that:
def authorization(self, data):
"""
Checking user with DB
"""
def __gotResult(user):
yield engine.execute(sqlalchemy.select([Users]).where(Users.name == user))
result = __gotResult(data['user'])
log.msg("[AUTH] User=%s trying to auth..." % data['user'])
data, result_msg = commands.AUTH(result, data)
log.msg(result_msg)
return data
And cant understand - what i doing wrong? Maybe issue in option for engine (where reactor=[])?
Source code:
import sys
from json import dumps, loads
import sqlalchemy
from twisted.internet import reactor, ssl
from twisted.python import log, logfile
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS
import commands
from db.tables import Users
from alchimia import TWISTED_STRATEGY
log_file = logfile.LogFile("service.log", ".")
log.startLogging(log_file)
engine = sqlalchemy.create_engine('postgresql://test:test#localhost/testdb', pool_size=20, max_overflow=0,strategy=TWISTED_STRATEGY, reactor=[])
class DFSServerProtocol(WebSocketServerProtocol):
commands = commands.commands_user
def __init__(self):
self.commands_handlers = self.__initHandlersUser()
def __initHandlersUser(self):
handlers = commands.commands_handlers_server
handlers['AUTH'] = self.authorization
handlers['READ'] = None
handlers['WRTE'] = None
handlers['DELT'] = None
handlers['RNME'] = None
handlers['SYNC'] = None
handlers['LIST'] = None
return handlers
def authorization(self, data):
"""
Checking user with DB
"""
def __gotResult(user):
yield engine.execute(sqlalchemy.select([Users]).where(Users.name == data['user']))
result = __gotResult(data['user'])
log.msg("[AUTH] User=%s trying to auth..." % data['user'])
data, result_msg = commands.AUTH(result, data)
log.msg(result_msg)
return data
def onMessage(self, payload, isBinary):
json_data = loads(payload)
json_auth = json_data['auth']
json_cmd = json_data['cmd']
if json_auth == False:
if json_cmd == 'AUTH':
json_data = self.commands_handlers['AUTH'](json_data)
# for authorized users
else:
if json_cmd in commands.commands_user.keys():
if self.commands_handlers[json_cmd] is not None:
json_data = self.commands_handlers[json_cmd](json_data)
else:
json_data['error'] = '%s command is not already realized...' % json_cmd
else:
json_data['auth'] = False
json_data['error'] = 'This command is not supported on server...'
response = dumps(json_data)
self.sendMessage(str(response))
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'debug':
log.startLogging(sys.stdout)
debug = True
else:
debug = False
contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt')
factory = WebSocketServerFactory("wss://localhost:9000", debug = debug, debugCodePaths = debug)
factory.protocol = DFSServerProtocol
factory.setProtocolOptions(allowHixie76 = True)
listenWS(factory, contextFactory)
webdir = File("./web/")
webdir.contentTypes['.crt'] = 'application/x-x509-ca-cert'
web = Site(webdir)
reactor.listenSSL(8080, web, contextFactory)
#reactor.listenTCP(8080, web)
reactor.run()
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/twisted/python/log.py", line 88, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/log.py", line 73, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 614, in _doReadOrWrite
why = selectable.doRead()
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 215, in doRead
return self._dataReceived(data)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 221, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/tls.py", line 419, in dataReceived
self._flushReceiveBIO()
File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/tls.py", line 389, in _flushReceiveBIO
ProtocolWrapper.dataReceived(self, bytes)
File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/policies.py", line 120, in dataReceived
self.wrappedProtocol.dataReceived(data)
File "/usr/local/lib/python2.7/dist-packages/autobahn/twisted/websocket.py", line 78, in dataReceived
self._dataReceived(data)
File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 1270, in _dataReceived
self.consumeData()
File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 1286, in consumeData
while self.processData() and self.state != WebSocketProtocol.STATE_CLOSED:
File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 1445, in processData
return self.processDataHybi()
File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 1758, in processDataHybi
fr = self.onFrameEnd()
File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 1887, in onFrameEnd
self._onMessageEnd()
File "/usr/local/lib/python2.7/dist-packages/autobahn/twisted/websocket.py", line 107, in _onMessageEnd
self.onMessageEnd()
File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 734, in onMessageEnd
self._onMessage(payload, self.message_is_binary)
File "/usr/local/lib/python2.7/dist-packages/autobahn/twisted/websocket.py", line 110, in _onMessage
self.onMessage(payload, isBinary)
File "server.py", line 84, in onMessage
json_data = self.commands_handlers['AUTH'](json_data)
File "server.py", line 68, in authorization
data, result_msg = commands.AUTH(result, data)
File "/home/relrin/code/Helenae/helenae/commands.py", line 68, in AUTH
if result['name'] == data['user']:
exceptions.TypeError: 'generator' object has no attribute '__getitem__'
I think you are missing an #inlineCallbacks around __gotResult() That might not help you quite enough, though; since a single statement generator wrapped with inlineCallbacks is sort of pointless. You should get used to working with explicit deferred handling anyway. Lets pull this apart:
def authorization(self, data):
"""
Checking user with DB
"""
# engine.execute already gives us a deferred, will grab on to that.
user = data['user']
result_d = engine.execute(sqlalchemy.select([Users]).where(Users.name == user))
# we don't have the result in authorization,
# we need to wrap any code that works with its result int a callback.
def result_cb(result):
data, result_msg = commands.AUTH(result, data)
return data
result_d.addCallback(result_cb)
# we want to pass the (asynchronous) result out, it's hiding in our deferred;
# so we return *that* instead; callers need to add more callbacks to it.
return result_d
If you insist; we can squish this down into an inline callbacks form:
from twisted.internet.defer import inlineCallbacks, returnValue
#inlineCallbacks
def authorization(self, data):
user = data['user']
result = yield engine.execute(sqlalchemy.select([Users]).where(Users.name == user))
data, result_msg = commands.AUTH(result, data)
yield returnValue(data)
as before, though, authorization() is asynchronous; and must be since engine.execute is async. to use it, you must attach a callback to the deferred it returns (although the caller may also yield it if it is also wrapped in inlineCallbacks

404 being returned by urllib2.urlopen(req) even though HTTP 200 being sent

I have the below python script that is making a successful rest web service request but then throwing a 404 after the server sends a HTTP 200 back. I can see the rest web service web app log returning the below JSON response successfully. Any ideas on how to further troubleshoot this or what could be causing the below error?
Last Python line executed:
result = urllib2.urlopen(req)
JSON response from Rest API Endpoint:
response{"status":"SUCCESS","reason":null,"location":null,"details":null,"errorDetails":{}}
Python Script:
#!/home/user/activepython-2.7.2.5_x86_64/bin/python
import sys
import os
import logging
import subprocess
import tempfile
import json
import urllib2
# define SVN
svn_repo = sys.argv[1]
svn_txn = sys.argv[2]
svn_opt = '-t'
# handle temp file
tmp_file = tempfile.NamedTemporaryFile(prefix="app_",
suffix=".tmp", dir="/tmp", delete=False)
delete_file = True
rest_url = 'https://host/rest/api/endpoint'
# setup logging
log_level = logging.DEBUG
logger = logging.getLogger("myapp")
logger.setLevel(log_level)
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(log_level)
logger.addHandler(handler)
def get_svn_changes():
cmd = "/home/user/bin/svnlook changed --copy-info %s %s %s" % (svn_opt, svn_txn, svn_repo)
output, return_code = command_output(cmd)
return output
def get_author():
cmd = "/home/csvn/bin/svnlook author %s %s %s" % (svn_opt, svn_txn, svn_repo)
author, return_code = command_output(cmd)
return author.strip()
def call_webservice():
req = urllib2.Request(rest_url)
req.add_header('Accept', 'arpplication/json')
req.add_header('Content-Type', 'application/json')
logger.debug("file=" + tmp_file.name)
data = json.dumps({"name" : "file", "value" : tmp_file.name})
logger.debug("data=" + data)
req.add_data(data)
logger.debug("request")
result = urllib2.urlopen(req)
logger.debug("result")
json_result = json.load(result)
logger.debug("json_result")
result_data = json.loads(json_result['response'])
logger.debug("result_data")
return result_data
if __name__ == "__main__":
exit_code = 0;
out_message = ''
author = get_author()
try:
tmp_file.write("author=%s\n" % author)
output = get_svn_changes()
tmp_file.write(output)
tmp_file.close()
output = call_webservice()
if (output['status'] == 'ERROR'):
out_message = output['reason']
exit_code = 1
except Exception, ex:
out_message = str(ex)
exit_code = 1
finally:
if (exit_code == 1):
sys.stderr.write("Error: %s" % out_message)
if delete_file:
os.remove(tmp_file.name)
sys.exit(exit_code)
Traceback Exception:
//startlogger output
file=/tmp/app_rrOgN0.tmp
data={"name": "file", "value": "/tmp/app_rrOgN0.tmp"}
request
//stop logger output
Traceback (most recent call last):
File "/home/csvn/data/repositories/repo/hooks/pre-commit", line 85, in <module>
output = call_webservice()
File "/home/csvn/data/repositories/repo/hooks/pre-commit", line 59, in call_webservice
result = urllib2.urlopen(req)
File "/home/activepython-2.7.2.5_x86_64/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/home/activepython-2.7.2.5_x86_64/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/home/activepython-2.7.2.5_x86_64/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/home/activepython-2.7.2.5_x86_64/lib/python2.7/urllib2.py", line 438, in error
return self._call_chain(*args)
File "/home/activepython-2.7.2.5_x86_64/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/home/activepython-2.7.2.5_x86_64/lib/python2.7/urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 404: Not Found
Error: HTTP Error 404: Not Found
You misspelled the Accept header:
req.add_header('Accept', 'arpplication/json')
Correct the spelling of application:
req.add_header('Accept', 'application/json')

Getting unhandled error and connection get lost when a client tries to communicate with chat server in twisted

from twisted.internet.protocol import Protocol,Factory
from twisted.internet import reactor
class ChatServer(Protocol):
def connectionMade(self):
print "A Client Has Connected"
self.factory.clients.append(self)
print"clients are ",self.factory.clients
self.transport.write('Hello,Welcome to the telnet chat to sign in type aim:YOUR NAME HERE to send a messsage type msg:YOURMESSAGE '+'\n')
def connectionLost(self,reason):
self.factory.clients.remove(self)
self.transport.write('Somebody was disconnected from the server')
def dataReceived(self,data):
#print "data is",data
a = data.split(':')
if len(a) > 1:
command = a[0]
content = a[1]
msg=""
if command =="iam":
self.name + "has joined"
elif command == "msg":
ma=sg = self.name + ":" +content
print msg
for c in self.factory.clients:
c.message(msg)
def message(self,message):
self.transport.write(message + '\n')
factory = Factory()
factory.protocol = ChatServer
factory.clients = []
reactor.listenTCP(80,factory)
print "Iphone Chat server started"
reactor.run()
The above code is running succesfully...but when i connect the client (by typing telnet localhost 80) to this chatserver and try to write message ,connection gets lost and following errors occurs :
Iphone Chat server started
A Client Has Connected
clients are [<__main__.ChatServer instance at 0x024AC0A8>]
Unhandled Error
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\context.py", line 81, in callWithContext
return func(*args,**kw)
--- ---
File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 150, in _doReadOrWrite
why = getattr(selectable, method)()
File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 199, in doRead
rval = self.protocol.dataReceived(data)
File "D:\chatserverultimate.py", line 21, in dataReceived
content = a[1]
exceptions.IndexError: list index out of range
Where am I going wrong?
You indented content = a[1] line incorrectly. You need more space(s)! :)

Categories

Resources