int treated as `self' in python3












0














I want to build a simple server that dispatches requests depending on their path. So I wrote the following code:



from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import socket

class Handler:
"""处理对应资源的请求"""
def __init__(self, dispatcher):
self.dispatcher = dispatcher

def handle(self):
"""根据dispatcher解析出来的path,调用对应的方法"""
command = 'do_' + self.dispatcher.command
print(command)
if not hasattr(self, command):
return;

method = getattr(self, command)
method(self)

def do_GET(self):
response = {
'message': 'message'
}
dispatcher.protocol_version = 'HTTP/1.1'
dispatcher.send_response(200, 'OK')
dispatcher.send_header('Content-type', 'text/plain')
dispatcher.wfile.write(bytes(json.dumps(response), 'utf-8'))

class dispatcher(BaseHTTPRequestHandler):
"""
根据url的不同分发请求
"""
def handle_one_request(self):
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
return
if not self.raw_requestline:
self.close_connection = True
return
if not self.parse_request():
# An error code has been sent, just exit
return
print(self.command)
print(self.path)
if self.path.startswith('/wrong'):
Handler(self).handle()
self.wfile.flush() #actually send the response if not already done.
except socket.timeout as e:
#a read or a write timed out. Discard this connection
self.log_error("Request timed out: %r", e)
self.close_connection = True
return

if __name__ == '__main__':
server = HTTPServer(('', 8080), dispatcher)
server.serve_forever()


The dispatcher will parse the incoming request and get the path so that it can decide which handler to call(though there is only one here for now).



In the handler class, it will call corresponding method based on the http method. In the do_GET method, it will call some methods in the dispatcher and that's where things go wrong.



When I ran this program and execute curl http://localhost:8080/wrong, I had the following exception:



GET
/wrong
do_GET
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 50072)
Traceback (most recent call last):
File "/usr/lib/python3.5/socketserver.py", line 313, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 341, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
self.handle()
File "/usr/lib/python3.5/http/server.py", line 422, in handle
self.handle_one_request()
File "hello.py", line 51, in handle_one_request
Handler(self).handle()
File "hello.py", line 18, in handle
method()
File "hello.py", line 25, in do_GET
dispatcher.send_response(200, 'OK')
File "/usr/lib/python3.5/http/server.py", line 487, in send_response
self.log_request(code)
AttributeError: 'int' object has no attribute 'log_request'
----------------------------------------


log_request is defined as follows in the super class of dispatcher:



def log_request(self, code='-', size='-'):
# blablabla


and it is called in dispatcher.send_response.



I guess the problem is that the 200 is treated as self by the interpreter.



If my guess is right, why is this happening?



If not, what causes this exception?



I know this question is still in the grammar level, but I'd appreciate it if someone can help me.










share|improve this question






















  • within do_GET you're using dispatcher instead of self.dispatcher :)
    – Wolph
    Nov 23 at 2:39










  • @Wolph thanks, problem solved. Never gonna to instantiate object with the same name of class again :D
    – Charles
    Nov 23 at 2:41






  • 1




    @Charles: This is part of the reason why PEP8 recommends the CapWords convention for class names (and nothing else); if the class is Dispatcher, then a variable named dispatcher isn't a problem, whether or not it's on self.
    – ShadowRanger
    Nov 23 at 2:49
















0














I want to build a simple server that dispatches requests depending on their path. So I wrote the following code:



from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import socket

class Handler:
"""处理对应资源的请求"""
def __init__(self, dispatcher):
self.dispatcher = dispatcher

def handle(self):
"""根据dispatcher解析出来的path,调用对应的方法"""
command = 'do_' + self.dispatcher.command
print(command)
if not hasattr(self, command):
return;

method = getattr(self, command)
method(self)

def do_GET(self):
response = {
'message': 'message'
}
dispatcher.protocol_version = 'HTTP/1.1'
dispatcher.send_response(200, 'OK')
dispatcher.send_header('Content-type', 'text/plain')
dispatcher.wfile.write(bytes(json.dumps(response), 'utf-8'))

class dispatcher(BaseHTTPRequestHandler):
"""
根据url的不同分发请求
"""
def handle_one_request(self):
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
return
if not self.raw_requestline:
self.close_connection = True
return
if not self.parse_request():
# An error code has been sent, just exit
return
print(self.command)
print(self.path)
if self.path.startswith('/wrong'):
Handler(self).handle()
self.wfile.flush() #actually send the response if not already done.
except socket.timeout as e:
#a read or a write timed out. Discard this connection
self.log_error("Request timed out: %r", e)
self.close_connection = True
return

if __name__ == '__main__':
server = HTTPServer(('', 8080), dispatcher)
server.serve_forever()


The dispatcher will parse the incoming request and get the path so that it can decide which handler to call(though there is only one here for now).



In the handler class, it will call corresponding method based on the http method. In the do_GET method, it will call some methods in the dispatcher and that's where things go wrong.



When I ran this program and execute curl http://localhost:8080/wrong, I had the following exception:



GET
/wrong
do_GET
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 50072)
Traceback (most recent call last):
File "/usr/lib/python3.5/socketserver.py", line 313, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 341, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
self.handle()
File "/usr/lib/python3.5/http/server.py", line 422, in handle
self.handle_one_request()
File "hello.py", line 51, in handle_one_request
Handler(self).handle()
File "hello.py", line 18, in handle
method()
File "hello.py", line 25, in do_GET
dispatcher.send_response(200, 'OK')
File "/usr/lib/python3.5/http/server.py", line 487, in send_response
self.log_request(code)
AttributeError: 'int' object has no attribute 'log_request'
----------------------------------------


log_request is defined as follows in the super class of dispatcher:



def log_request(self, code='-', size='-'):
# blablabla


and it is called in dispatcher.send_response.



I guess the problem is that the 200 is treated as self by the interpreter.



If my guess is right, why is this happening?



If not, what causes this exception?



I know this question is still in the grammar level, but I'd appreciate it if someone can help me.










share|improve this question






















  • within do_GET you're using dispatcher instead of self.dispatcher :)
    – Wolph
    Nov 23 at 2:39










  • @Wolph thanks, problem solved. Never gonna to instantiate object with the same name of class again :D
    – Charles
    Nov 23 at 2:41






  • 1




    @Charles: This is part of the reason why PEP8 recommends the CapWords convention for class names (and nothing else); if the class is Dispatcher, then a variable named dispatcher isn't a problem, whether or not it's on self.
    – ShadowRanger
    Nov 23 at 2:49














0












0








0







I want to build a simple server that dispatches requests depending on their path. So I wrote the following code:



from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import socket

class Handler:
"""处理对应资源的请求"""
def __init__(self, dispatcher):
self.dispatcher = dispatcher

def handle(self):
"""根据dispatcher解析出来的path,调用对应的方法"""
command = 'do_' + self.dispatcher.command
print(command)
if not hasattr(self, command):
return;

method = getattr(self, command)
method(self)

def do_GET(self):
response = {
'message': 'message'
}
dispatcher.protocol_version = 'HTTP/1.1'
dispatcher.send_response(200, 'OK')
dispatcher.send_header('Content-type', 'text/plain')
dispatcher.wfile.write(bytes(json.dumps(response), 'utf-8'))

class dispatcher(BaseHTTPRequestHandler):
"""
根据url的不同分发请求
"""
def handle_one_request(self):
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
return
if not self.raw_requestline:
self.close_connection = True
return
if not self.parse_request():
# An error code has been sent, just exit
return
print(self.command)
print(self.path)
if self.path.startswith('/wrong'):
Handler(self).handle()
self.wfile.flush() #actually send the response if not already done.
except socket.timeout as e:
#a read or a write timed out. Discard this connection
self.log_error("Request timed out: %r", e)
self.close_connection = True
return

if __name__ == '__main__':
server = HTTPServer(('', 8080), dispatcher)
server.serve_forever()


The dispatcher will parse the incoming request and get the path so that it can decide which handler to call(though there is only one here for now).



In the handler class, it will call corresponding method based on the http method. In the do_GET method, it will call some methods in the dispatcher and that's where things go wrong.



When I ran this program and execute curl http://localhost:8080/wrong, I had the following exception:



GET
/wrong
do_GET
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 50072)
Traceback (most recent call last):
File "/usr/lib/python3.5/socketserver.py", line 313, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 341, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
self.handle()
File "/usr/lib/python3.5/http/server.py", line 422, in handle
self.handle_one_request()
File "hello.py", line 51, in handle_one_request
Handler(self).handle()
File "hello.py", line 18, in handle
method()
File "hello.py", line 25, in do_GET
dispatcher.send_response(200, 'OK')
File "/usr/lib/python3.5/http/server.py", line 487, in send_response
self.log_request(code)
AttributeError: 'int' object has no attribute 'log_request'
----------------------------------------


log_request is defined as follows in the super class of dispatcher:



def log_request(self, code='-', size='-'):
# blablabla


and it is called in dispatcher.send_response.



I guess the problem is that the 200 is treated as self by the interpreter.



If my guess is right, why is this happening?



If not, what causes this exception?



I know this question is still in the grammar level, but I'd appreciate it if someone can help me.










share|improve this question













I want to build a simple server that dispatches requests depending on their path. So I wrote the following code:



from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import socket

class Handler:
"""处理对应资源的请求"""
def __init__(self, dispatcher):
self.dispatcher = dispatcher

def handle(self):
"""根据dispatcher解析出来的path,调用对应的方法"""
command = 'do_' + self.dispatcher.command
print(command)
if not hasattr(self, command):
return;

method = getattr(self, command)
method(self)

def do_GET(self):
response = {
'message': 'message'
}
dispatcher.protocol_version = 'HTTP/1.1'
dispatcher.send_response(200, 'OK')
dispatcher.send_header('Content-type', 'text/plain')
dispatcher.wfile.write(bytes(json.dumps(response), 'utf-8'))

class dispatcher(BaseHTTPRequestHandler):
"""
根据url的不同分发请求
"""
def handle_one_request(self):
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
return
if not self.raw_requestline:
self.close_connection = True
return
if not self.parse_request():
# An error code has been sent, just exit
return
print(self.command)
print(self.path)
if self.path.startswith('/wrong'):
Handler(self).handle()
self.wfile.flush() #actually send the response if not already done.
except socket.timeout as e:
#a read or a write timed out. Discard this connection
self.log_error("Request timed out: %r", e)
self.close_connection = True
return

if __name__ == '__main__':
server = HTTPServer(('', 8080), dispatcher)
server.serve_forever()


The dispatcher will parse the incoming request and get the path so that it can decide which handler to call(though there is only one here for now).



In the handler class, it will call corresponding method based on the http method. In the do_GET method, it will call some methods in the dispatcher and that's where things go wrong.



When I ran this program and execute curl http://localhost:8080/wrong, I had the following exception:



GET
/wrong
do_GET
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 50072)
Traceback (most recent call last):
File "/usr/lib/python3.5/socketserver.py", line 313, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 341, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
self.handle()
File "/usr/lib/python3.5/http/server.py", line 422, in handle
self.handle_one_request()
File "hello.py", line 51, in handle_one_request
Handler(self).handle()
File "hello.py", line 18, in handle
method()
File "hello.py", line 25, in do_GET
dispatcher.send_response(200, 'OK')
File "/usr/lib/python3.5/http/server.py", line 487, in send_response
self.log_request(code)
AttributeError: 'int' object has no attribute 'log_request'
----------------------------------------


log_request is defined as follows in the super class of dispatcher:



def log_request(self, code='-', size='-'):
# blablabla


and it is called in dispatcher.send_response.



I guess the problem is that the 200 is treated as self by the interpreter.



If my guess is right, why is this happening?



If not, what causes this exception?



I know this question is still in the grammar level, but I'd appreciate it if someone can help me.







python python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 at 2:34









Charles

2816




2816












  • within do_GET you're using dispatcher instead of self.dispatcher :)
    – Wolph
    Nov 23 at 2:39










  • @Wolph thanks, problem solved. Never gonna to instantiate object with the same name of class again :D
    – Charles
    Nov 23 at 2:41






  • 1




    @Charles: This is part of the reason why PEP8 recommends the CapWords convention for class names (and nothing else); if the class is Dispatcher, then a variable named dispatcher isn't a problem, whether or not it's on self.
    – ShadowRanger
    Nov 23 at 2:49


















  • within do_GET you're using dispatcher instead of self.dispatcher :)
    – Wolph
    Nov 23 at 2:39










  • @Wolph thanks, problem solved. Never gonna to instantiate object with the same name of class again :D
    – Charles
    Nov 23 at 2:41






  • 1




    @Charles: This is part of the reason why PEP8 recommends the CapWords convention for class names (and nothing else); if the class is Dispatcher, then a variable named dispatcher isn't a problem, whether or not it's on self.
    – ShadowRanger
    Nov 23 at 2:49
















within do_GET you're using dispatcher instead of self.dispatcher :)
– Wolph
Nov 23 at 2:39




within do_GET you're using dispatcher instead of self.dispatcher :)
– Wolph
Nov 23 at 2:39












@Wolph thanks, problem solved. Never gonna to instantiate object with the same name of class again :D
– Charles
Nov 23 at 2:41




@Wolph thanks, problem solved. Never gonna to instantiate object with the same name of class again :D
– Charles
Nov 23 at 2:41




1




1




@Charles: This is part of the reason why PEP8 recommends the CapWords convention for class names (and nothing else); if the class is Dispatcher, then a variable named dispatcher isn't a problem, whether or not it's on self.
– ShadowRanger
Nov 23 at 2:49




@Charles: This is part of the reason why PEP8 recommends the CapWords convention for class names (and nothing else); if the class is Dispatcher, then a variable named dispatcher isn't a problem, whether or not it's on self.
– ShadowRanger
Nov 23 at 2:49

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440004%2fint-treated-as-self-in-python3%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440004%2fint-treated-as-self-in-python3%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Contact image not getting when fetch all contact list from iPhone by CNContact

count number of partitions of a set with n elements into k subsets

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks