ladon throwing an AttributeError - python

I'm trying to get ladon working, however, I don't seem to be able to define the service properly.
Specifically, even with a minimal test case, it's throwing
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\ladon\server\wsgi_application.py", line 332, in __call__
self.import_services(self.service_list)
File "C:\Python33\lib\site-packages\ladon\server\wsgi_application.py", line 288, in import_services
__import__(service)
File "D:\Workspaces\Python\SOAPManager.py", line 20, in <module>
#ladonize(PORTABLE_STRING, PORTABLE_STRING, rtype=PORTABLE_STRING)
File "C:\Python33\lib\site-packages\ladon\ladonizer\decorator.py", line 118, in decorator
injector.__doc__ = ladon_method_info._doc
AttributeError: 'NoneType' object has no attribute '_doc'
My Run.py contains:
from ladon.server.wsgi import LadonWSGIApplication
from os.path import abspath, dirname
from wsgiref.simple_server import make_server
application = LadonWSGIApplication(
['SOAPManager'],
[dirname(abspath(__file__))],
catalog_name='API',
catalog_desc='API Description')
httpd = make_server('0.0.0.0', 8004, application)
print("Listening on port 8004...")
# Respond to requests until process is killed
httpd.serve_forever()
And the minimal test case in SOAPManager.py:
from ladon.ladonizer import ladonize
from ladon.types.ladontype import LadonType
from ladon.compat import PORTABLE_STRING
#ladonize(PORTABLE_STRING, PORTABLE_STRING, rtype=PORTABLE_STRING)
def Authenticate(Username, Password):
return "Test"
The error is being raised from within the ladonize decorator. It seems to be occuring when trying to build up the definition of the service. Specifically, in ladon the decorator calls collection.add_service_method which returns None instead of a method. I think it's failing a line-number check.
firstlineno = f.__code__.co_firstlineno
# get an ast-analyzed object of the source file
sinfo = self.source_info(src_fname)
...
for clsname,v in sinfo.items():
if firstlineno>v[0] and firstlineno<=v[1]:
For some reason that check is failing so the method defaults to returning None.

Related

AttributeError: loop attribute cannot be accessed in non-async contexts

When I do python main.py this error pops up -
Traceback (most recent call last):
File "C:\Users\Anju Tiwari\Desktop\DiscordDashboard-main\backend\main.py", line 15, in <module>
run()
File "C:\Users\Anju Tiwari\Desktop\DiscordDashboard-main\backend\main.py", line 10, in run
mybot.loop.create_task(app.run_task(host=os.getenv("HOST"),port=os.getenv("PORT")))
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Anju Tiwari\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 108, in __getattr__
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
My main.py file -
import os
from bot import mybot
from web import app
from utils.logger import log_info
from dotenv import load_dotenv
load_dotenv(verbose=True)
def run():
log_info("Create Web server task...")
mybot.loop.create_task(app.run_task(host=os.getenv("HOST"),port=os.getenv("PORT")))
log_info("Start bot...")
mybot.run(os.getenv("BOT_TOKEN"))
log_info("Successfully started Web server and Bot!")
if __name__ == "__main__":
run()
I also downloaded dotenv properly and it's still not working someoe poeple help me.

Twisted HTTPS Client

I am currently having some trouble accessing content hosted via https using the twisted python library. I am new to this library, and am assuming there is some concept I am missing that's causing the issue, but perhaps not based upon the example.
Here is a link to the page in which I gathered the example:
https://twistedmatrix.com/documents/current/web/howto/client.html
Under the heading HTTP over SSL
from twisted.python.log import err
from twisted.web.client import Agent
from twisted.internet import reactor
from twisted.internet.ssl import optionsForClientTLS
def display(response):
print("Received response")
print(response)
def main():
contextFactory = optionsForClientTLS(u"https://example.com/")
agent = Agent(reactor, contextFactory)
d = agent.request("GET", "https://example.com/")
d.addCallbacks(display, err)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()
if __name__ == "__main__":
main()
When running this code, it straight up fails. I get an error that looks like this:
Traceback (most recent call last):
File "https.py", line 19, in <module>
main()
File "https.py", line 11, in main
contextFactory = optionsForClientTLS(u"https://example.com/")
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1336, in optionsForClientTLS
return ClientTLSOptions(hostname, certificateOptions.getContext())
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1198, in __init__
self._hostnameBytes = _idnaBytes(hostname)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 86, in _idnaBytes
return idna.encode(text)
File "/usr/local/lib/python2.7/dist-packages/idna/core.py", line 355, in encode
result.append(alabel(label))
File "/usr/local/lib/python2.7/dist-packages/idna/core.py", line 276, in alabel
check_label(label)
File "/usr/local/lib/python2.7/dist-packages/idna/core.py", line 253, in check_label
raise InvalidCodepoint('Codepoint {0} at position {1} of {2} not allowed'.format(_unot(cp_value), pos+1, repr(label)))
idna.core.InvalidCodepoint: Codepoint U+003A at position 6 of u'https://example' not allowed
This error lead me to believe the parameter being passed into optionsForClientTLS were incorrect. It calls for a hostname and not a full url, so I shortened the parameter to simply example.com. Once that change was made, the function completed successfully.
Unfortunately though, after making the change, the script now failed at the line invoking agent.request. The error it supplied was this:
Traceback (most recent call last):
File "https.py", line 19, in <module>
main()
File "https.py", line 13, in main
d = agent.request("GET", "https://example.com/")
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1596, in request
endpoint = self._getEndpoint(parsedURI)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1580, in _getEndpoint
return self._endpointFactory.endpointForURI(uri)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1456, in endpointForURI
uri.port)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 982, in creatorForNetloc
context = self._webContextFactory.getContext(hostname, port)
AttributeError: 'ClientTLSOptions' object has no attribute 'getContext'
This error leads me to believe that the object being produced by optionsForClientTLS is not the object type that is expected to be passed into the Agent upon creation. A function is trying to be invoked that does not exist. With all that said, I have two questions.
Is this example deprecated? The previous examples that make http requests all work like a charm. Am I doing something wrong, or is the example no longer valid?
I am only looking for a simple way to retrieve data from a server using HTTPS. If doing things this way is not the solution, is anyone familiar with how HTTPS requests can be made using twisted?
Yes you're absolutely correct that the example on the docs is wrong. I noticed the bug while working w/ treq. Try following this example from v14. With that being said, you should use treq as opposed to trying to use Twisted directly. Most of the heavy lifting has been taken care of for you. Here's an simple conversion of your example:
from __future__ import print_function
import treq
from twisted.internet import defer, task
from twisted.python.log import err
#defer.inlineCallbacks
def display(response):
content = yield treq.content(response)
print('Content: {0}'.format(content))
def main(reactor):
d = treq.get('https://twistedmatrix.com')
d.addCallback(display)
d.addErrback(err)
return d
task.react(main)
As you can see treq takes care of the SSL stuff for you. The display() callback function can be used to extract various components of the HTTP response, such as headers, status codes, body, etc. If you only need a single component, such as the response body, then you can simplify further like so:
def main(reactor):
d = treq.get('https://twistedmatrix.com')
d.addCallback(treq.content) # get response content when available
d.addErrback(err)
d.addCallback(print)
return d
task.react(main)

Python - Fabric - Getting files

I am trying to write a simple python code with fabric to transfer a file from one host to another using the get() function although I keep getting error message:
MacBook-Pro-3:PythonsScripts$ fab get:'/tmp/test','/tmp/test'
[hostname] Executing task 'get'
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/fabric/main.py", line 743, in main
*args, **kwargs
File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 387, in execute
multiprocessing
File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 277, in _execute
return task.run(*args, **kwargs)
File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 174, in run
return self.wrapped(*args, **kwargs)
File "/Users/e0126914/Desktop/PYTHON/PythonsScripts/fabfile.py", line 128, in get
get('/tmp/test','/tmp/test') ***This line repeats many times then last error below***
RuntimeError: maximum recursion depth exceeded
My current code is:
from fabric.api import *
from getpass import getpass
from fabric.decorators import runs_once
env.hosts = ['hostname']
env.port = '22'
env.user = 'parallels'
env.password="password"
def abc(remote_path, local_path):
abc('/tmp/test','/tmp/')
Any help would be appreciated!
fabric.api.get already is a method. When you perform from fabric.api import * you are importing fabric's get. You should rename your get function to avoid conflict.
From inside the abc function, you need to call get
def abc(p1,p2):
get(p1, p2)
EDIT:
When executing functions through fabric, the arguments are passed through the command line
ie. $ fab abc:string1,string2

Errors when connecting to router with python code

I am trying to connect to some router using the above code and I am using juniperj2320.py module and in test file I have
am using code base from this http://subversion.assembla.com/svn/clauzsistel08/trunk/dist/
#!/usr/bin/python
from localconf import *
from juniperj2320 import *
import sys
import traceback
SERIALDEVICE = '/dev/ttyUSB0'
# Now configure the router
try:
router = JuniperJ2320(SERIALDEVICE)
except RouterConfigurationException, err:
print "Router configuration error: ", err
print "Please try again."
sys.exit(1)
but am getting this following error
./test.py
> /root/pyserial-2.6/examples/serialrouter.py(37)__init__()
-> serial.Serial.__init__(self, serialdevice, baudrate=baudrate, \
(Pdb) c
Traceback (most recent call last):
File "./test.py", line 30, in
router = JuniperJ2320(SERIALDEVICE)
File "/root/pyserial-2.6/examples/juniperj2320.py", line 32, in __init__
BYTESIZE, PARITY, STOPBITS, TIMEOUT)
File "/root/pyserial-2.6/examples/serialrouter.py", line 44, in __init__
fdpexpect.fdspawn.__init__(self, self.fileno())
File "/usr/lib/python2.6/site-packages/fdpexpect.py", line 40, in __init__
spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile )
File "/usr/lib/python2.6/site-packages/pexpect.py", line 412, in __init__
self.closed = True # File-like object.
AttributeError: can't set attribute
and absolutely clue less on wat happening here ! any help ll be greatly appreciated
thanks
This is a little bit of a shot in the dark, because I'm not familiar with the modules you're using, but based on the traceback, it looks like the constructor is expecting a file-like object, not just a file path. Try this instead.
SERIALDEVICE = '/dev/ttyUSB0'
# Now configure the router
try:
router = JuniperJ2320(open(SERIALDEVICE))
Instead of writing your own serial communications program wouldn't be easier to have pexpect drive a serial program like minicom?

how to use pywhois module in gae

I have problems when try to import pywhois module, i can import my own module but still have troubles when import pywhois. I moved the pywhois folder in my project folder domain, the screentshot is below:
This is the import and calling statment below:
import part:
from pywhois import *
calling part:
w = whois('hackbo.com')
self.response.out.write(w)
The problems is it will always throw a http 500 error, error text is below:
Traceback (most recent call last):
File "/home/li/Desktop/google_appengine/google/appengine/ext/webapp/__init__.py", line 700, in __call__
handler.get(*groups)
File "/home/li/Desktop/google_appengine/domain/main.py", line 43, in get
w = whois('hackbo.com')
File "pywhois/__init__.py", line 12, in whois
text = nic_client.whois_lookup(None, domain, 0)
File "pywhois/whois.py", line 157, in whois_lookup
result = self.whois(query_arg, nichost, flags)
File "pywhois/whois.py", line 100, in whois
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
AttributeError: 'module' object has no attribute 'socket'
What is this error means? why i could import my own module but can not import pywhois?
Google App Engine doesn't support the socket module, which pywhois uses. It allows you to import socket, but it's an empty module.
import whois
site = input ("Enter Site : ")
n = whois.whois (site)
print (n)
this is best whois
Enjoy that, easy.

Categories

Resources