FastApi: App startup hangs at Router URL parsing - python

I'm writing a fastapi app with simple routers, when I try to start the app the start-up hangs at URL parsing in the re module. Please find the stack trace on KeyboardInterrupt below.
Traceback (most recent call last):
File "/Users/ssekar/ssa/code/classifier-api/app/main.py", line 7, in <module>
from app.api.classification_api import router as api_router
File "/Users/ssekar/ssa/code/classifier-api/app/api/classification_api.py", line 22, in <module>
router.include_router(
File "/Users/ssekar/Library/Caches/pypoetry/virtualenvs/classifier-api-MVO9j3br-py3.8/lib/python3.8/site-packages/fastapi/routing.py", line 569, in include_router
self.add_api_route(
File "/Users/ssekar/Library/Caches/pypoetry/virtualenvs/classifier-api-MVO9j3br-py3.8/lib/python3.8/site-packages/fastapi/routing.py", line 439, in add_api_route
route = route_class(
File "/Users/ssekar/Library/Caches/pypoetry/virtualenvs/classifier-api-MVO9j3br-py3.8/lib/python3.8/site-packages/fastapi/routing.py", line 290, in __init__
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
File "/Users/ssekar/Library/Caches/pypoetry/virtualenvs/classifier-api-MVO9j3br-py3.8/lib/python3.8/site-packages/starlette/routing.py", line 123, in compile_path
return re.compile(path_regex), path_format, param_convertors
File "/usr/local/opt/python#3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/re.py", line 252, in compile
return _compile(pattern, flags)
File "/usr/local/opt/python#3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/re.py", line 304, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/local/opt/python#3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sre_compile.py", line 764, in compile
p = sre_parse.parse(p, flags)
File "/usr/local/opt/python#3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sre_parse.py", line 948, in parse
p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
File "/usr/local/opt/python#3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sre_parse.py", line 443, in _parse_sub
itemsappend(_parse(source, state, verbose, nested + 1,
File "/usr/local/opt/python#3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sre_parse.py", line 529, in _parse
subpatternappend((LITERAL, _ord(this)))
KeyboardInterrupt
The code
from fastapi import APIRouter
from starlette import status
from starlette.responses import JSONResponse
from app.services.metedata_services import get_categories
router = APIRouter()
#router.get(
"/categories",
status_code=status.HTTP_200_OK,
)
def categories(tree: str):
.....
return JSONResponse(content=response)
router.include_router(
router,
tags=["categories"],
prefix="/v1",
)

You should call the include_router(...)--(FastAPI Doc) method of FastAPI class, not APIRouter
# some_app/api/routers.py
from fastapi import APIRouter
from starlette import status
from starlette.responses import JSONResponse
router = APIRouter()
#router.get(
"/categories",
status_code=status.HTTP_200_OK,
)
def categories(tree: str):
response = {"foo": "bar"}
return JSONResponse(content=response)
# main.py
import uvicorn
from fastapi import FastAPI
from some_app.api.routers import router
app = FastAPI()
app.include_router(
router,
tags=["categories"],
prefix="/v1",
)
if __name__ == "__main__":
uvicorn.run(app)

Related

Circular import with beanie ODM

I need to use a cross-reference in my MongoDB schema. I use beanie as ODM. Here is my models:
entity.py
from beanie import Document
class Entity(Document):
path: List["Folder"] = []
folder.py
from entity import Entity
class Folder(Entity)
pass
init_beanie.py
import beanie
from motor.motor_asyncio import AsyncIOMotorClient
from entity import Entity
from folder import Folder
models = [Entity, Folder]
async def init_beanie():
client = AsyncIOMotorClient("mongo-uri")
Entity.update_forward_refs(Folder=Folder)
await beanie.init_beanie(database=client["mongo-db-name"], document_models=models)
main.py
from fastapi import FastAPI
from init_beanie import init_beanie
my_app = FastAPI()
#my_app.on_event("startup")
async def init():
await init_beanie()
But when I start my app I got an erorr:
...
File "pydantic/main.py", line 816, in pydantic.main.BaseModel.update_forward_refs
File "pydantic/typing.py", line 553, in pydantic.typing.update_model_forward_refs
File "pydantic/typing.py", line 519, in pydantic.typing.update_field_forward_refs
File "pydantic/typing.py", line 65, in pydantic.typing.evaluate_forwardref
File "/usr/local/lib/python3.9/typing.py", line 554, in _evaluate
eval(self.__forward_code__, globalns, localns),
File "<string>", line 1, in <module>
NameError: name 'Folder' is not defined
what am I doing wrong?

KeyError: <weakref at 0x7fc9e8267ad0; to 'Flask' at 0x7fc9e9ec5750>

I've been having a hard time handling sessions in flask. Since when I manage the application in the local environment everything works perfectly, including flask sessions. But when i already host it in Render i always get this error in every route.
[55] [ERROR] Error handling request /valle-de-guadalupe
Traceback (most recent call last):
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/opt/render/project/src/app_folder/routes/public.py", line 35, in valle_de_guadalupe
return render_template("public/cities/valle_guadalupe.html")
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/templating.py", line 147, in render_template
return _render(app, template, context)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/templating.py", line 128, in _render
app.update_template_context(context)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 994, in update_template_context
context.update(func())
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/utils.py", line 407, in _user_context_processor
return dict(current_user=_get_user())
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/utils.py", line 372, in _get_user
current_app.login_manager._load_user()
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/login_manager.py", line 364, in _load_user
user = self._user_callback(user_id)
File "/opt/render/project/src/app.py", line 52, in load_user
return User.get_by_id(int(user_id))
File "/opt/render/project/src/app_folder/models/models.py", line 82, in get_by_id
return User.query.get(id)
File "<string>", line 2, in get
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/util/deprecations.py", line 402, in warned
return fn(*args, **kwargs)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 947, in get
return self._get_impl(ident, loading.load_on_pk_identity)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 959, in _get_impl
execution_options=self._execution_options,
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2959, in _get_impl
load_options=load_options,
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/loading.py", line 534, in load_on_pk_identity
bind_arguments=bind_arguments,
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1702, in execute
bind = self.get_bind(**bind_arguments)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_sqlalchemy/session.py", line 61, in get_bind
engines = self._db.engines
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_sqlalchemy/extension.py", line 629, in engines
return self._app_engines[app]
File "/usr/local/lib/python3.7/weakref.py", line 396, in __getitem__
return self.data[ref(key)]
KeyError: <weakref at 0x7fc9e8267ad0; to 'Flask' at 0x7fc9e9ec5750>
index.py
from app import app
from app_folder.utils.db import db
db.init_app(app)
with app.app_context():
db.create_all()
if __name__ == "__main__":
app.run(
debug = False,
port = 5000
)
app.py
from flask import Flask
"""Flask SqlAlchemy"""
from flask_sqlalchemy import SQLAlchemy
"""Flask Login"""
from flask_login import LoginManager
"""Dot Env"""
from dotenv import load_dotenv
"""App Folder Routes"""
from app_folder.handlers.stripe_handlers import stripe_error
from app_folder.handlers.web_handlers import web_error
from app_folder.models.models import User
from app_folder.routes.admin import admin
from app_folder.routes.public import public
from app_folder.routes.users import users
from app_folder.utils.db import db
"""Imports"""
import os
import stripe
load_dotenv()
"""config app"""
app = Flask(__name__,
static_url_path="",
template_folder="app_folder/templates",
static_folder="app_folder/static")
app.config['SECRET_KEY'] = os.getenv("SECRET_KEY")
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("SQLALCHEMY_DATABASE_VERSION")+os.getenv("SQLALCHEMY_USERNAME")+":"+os.getenv("SQLALCHEMY_PASSWORD")+"#"+os.getenv("SQLALCHEMY_SERVER")+"/"+os.getenv("SQLALCHEMY_DATABASE")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = os.getenv("SQLALCHEMY_TRACK_MODIFICATIONS")
"""blueprints"""
app.register_blueprint(stripe_error)
app.register_blueprint(web_error)
app.register_blueprint(admin)
app.register_blueprint(public)
app.register_blueprint(users)
SQLAlchemy(app)
login_manager = LoginManager(app)
""" stripe """
stripe_keys = {
'secret_key': os.getenv("STRIPE_SECRET_KEY"),
'publishable_key': os.getenv("STRIPE_PUBLISHABLE_KEY")
}
stripe.api_key = stripe_keys['secret_key']
"""Login Manager"""
#login_manager.user_loader
def load_user(user_id):
return User.get_by_id(int(user_id))
"""Teardown"""
#app.teardown_appcontext
def shutdown_session(exception=None):
db.session.remove()
Regardless of which route i'm on, while handling sessions I get the same error, but in this case use this path.
public.py
"""routes"""
#public.route("/", methods=["GET", "POST"])
def index():
return redirect(url_for('public.valle_de_guadalupe'))
"""cities"""
#public.route("/valle-de-guadalupe", methods=["GET", "POST"])
def valle_de_guadalupe():
return render_template("public/cities/valle_guadalupe.html")
I don't know if this has happened to someone else.
It's usually best to remove as many extra components and identify a minimal example that produces the error, otherwise it's often hard to help.
That said, I think that error suggests that db (SQLAlachemy() from flask-sqlalchemy) is not being inited with app.
I'm not sure what the db is that is being imported from app_folder.utils.db, but it appears that you may need to call db.init_app(app).
Relatedly, the line SQLAlchemy(app) is not being assigned. Perhaps you meant to assign that to db?
Other people report that this issue happens since the upgrade from flask-sqlalchemy v2.5.1 to v3. So downgrading might be a work around (not a permanent solution)
Source

Celery + Azure Service Bus (Broker) = claim is empty or token is invalid

I am trying to use Azure Service Bus as the broker for my celery app.
I have patched the solution by referring to various sources.
The goal is to use Azure Service Bus as the broker and PostgresSQL as the backend.
I created an Azure Service Bus and copied the credentials for the RootManageSharedAccessKey to the celery app.
Following is the task.py
from time import sleep
from celery import Celery
from kombu.utils.url import safequote
SAS_policy = safequote("RootManageSharedAccessKey") #SAS Policy
SAS_key = safequote("1234222zUY28tRUtp+A2YoHmDYcABCD") #Primary key from the previous SS
namespace = safequote("bluenode-dev")
app = Celery('tasks', backend='db+postgresql://afsan.gujarati:admin#localhost/local_dev',
broker=f'azureservicebus://{SAS_policy}:{SAS_key}=#{namespace}')
#app.task
def divide(x, y):
sleep(30)
return x/y
When I try to run the Celery app using the following command:
celery -A tasks worker --loglevel=INFO
I get the following error
[2020-10-09 14:00:32,035: CRITICAL/MainProcess] Unrecoverable error: AzureHttpError('Unauthorized\n<Error><Code>401</Code><Detail>claim is empty or token is invalid. TrackingId:295f7c76-770e-40cc-8489-e0eb56248b09_G5S1, SystemTracker:bluenode-dev.servicebus.windows.net:$Resources/Queues, Timestamp:2020-10-09T20:00:31</Detail></Error>')
Traceback (most recent call last):
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/transport/virtual/base.py", line 918, in create_channel
return self._avail_channels.pop()
IndexError: pop from empty list
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/azure/servicebus/control_client/servicebusservice.py", line 1225, in _perform_request
resp = self._filter(request)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/azure/servicebus/control_client/_http/httpclient.py", line 211, in perform_request
raise HTTPError(status, message, respheaders, respbody)
azure.servicebus.control_client._http.HTTPError: Unauthorized
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/worker/worker.py", line 203, in start
self.blueprint.start(self)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/bootsteps.py", line 116, in start
step.start(parent)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/bootsteps.py", line 365, in start
return self.obj.start()
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 311, in start
blueprint.start(self)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/bootsteps.py", line 116, in start
step.start(parent)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/worker/consumer/connection.py", line 21, in start
c.connection = c.connect()
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 398, in connect
conn = self.connection_for_read(heartbeat=self.amqheartbeat)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 404, in connection_for_read
return self.ensure_connected(
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 430, in ensure_connected
conn = conn.ensure_connection(
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/connection.py", line 383, in ensure_connection
self._ensure_connection(*args, **kwargs)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/connection.py", line 435, in _ensure_connection
return retry_over_time(
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/utils/functional.py", line 325, in retry_over_time
return fun(*args, **kwargs)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/connection.py", line 866, in _connection_factory
self._connection = self._establish_connection()
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/connection.py", line 801, in _establish_connection
conn = self.transport.establish_connection()
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/transport/virtual/base.py", line 938, in establish_connection
self._avail_channels.append(self.create_channel(self))
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/transport/virtual/base.py", line 920, in create_channel
channel = self.Channel(connection)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/kombu/transport/azureservicebus.py", line 64, in __init__
for queue in self.queue_service.list_queues():
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/azure/servicebus/control_client/servicebusservice.py", line 313, in list_queues
response = self._perform_request(request)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/azure/servicebus/control_client/servicebusservice.py", line 1227, in _perform_request
return _service_bus_error_handler(ex)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/azure/servicebus/control_client/_serialization.py", line 569, in _service_bus_error_handler
return _general_error_handler(http_error)
File "/Users/afsan.gujarati/.pyenv/versions/3.8.1/envs/celery-servicebus/lib/python3.8/site-packages/azure/servicebus/control_client/_common_error.py", line 41, in _general_error_handler
raise AzureHttpError(message, http_error.status)
azure.common.AzureHttpError: Unauthorized
<Error><Code>401</Code><Detail>claim is empty or token is invalid. TrackingId:295f7c76-770e-40cc-8489-e0eb56248b09_G5S1, SystemTracker:bluenode-dev.servicebus.windows.net:$Resources/Queues, Timestamp:2020-10-09T20:00:31</Detail></Error>
I don't see a straight solution for this anywhere. What am I missing?
P.S. I did not create the Queue in Azure Service Bus. I am assuming that celery would create the Queue by itself when the celery app is executed.
P.S.S. I also tried to use the exact same credentials in Python's Service Bus Client and it seemed to work. It feels like a Celery issue, but I am not able to figure out exactly what.
If you want to use Azure Service Bus Transport to connect Azure service bus, the URL should be azureservicebus://{SAS policy name}:{SAS key}#{Service Bus Namespace}.
For example
Get Shared access policies RootManageSharedAccessKey
Code
from celery import Celery
from kombu.utils.url import safequote
SAS_policy = "RootManageSharedAccessKey" # SAS Policy
# Primary key from the previous SS
SAS_key = safequote("X/*****qyY=")
namespace = "bowman1012"
app = Celery('tasks', backend='db+postgresql://<>#localhost/<>',
broker=f'azureservicebus://{SAS_policy}:{SAS_key}#{namespace}')
#app.task
def add(x, y):
return x + y

AXL Python getLine using pattern instead of uuid does not work (CUCM 11.5)

I'm struggling with getting for example line info via getLine using pattern instead of uuid. According to getLine AXL schema for CUCM 11.5 it should be possible to choose either uuid or pattern as lookup criteria. The python (2.7) module that I'm using is suds-jurko 0.6.
Base code is as follows:
from suds.client import Client
import ssl
wsdl = 'file:///C:/Users/xyz/Documents/axlplugin/schema/current/AXLAPI.wsdl'
location = 'https://10.10.20.1/axl/'
username = '***'
password = '***'
ssl._create_default_https_context = ssl._create_unverified_context
client = Client(wsdl, location=location, username=username, password=password)
First of all, the proof that the pattern I want to use as a lookup string for getLine actually exists:
>>> line2 = client.service.listLine({'pattern': '1018'}, returnedTags={'description': ''})
>>> line2
(reply){
return =
(return){
line[] =
(LLine){
_uuid = "{1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF}"
description = None
},
}
}
Then, I try getLine using uuid which works well:
>>> line5 = client.service.getLine('1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF')
>>> line5
(reply){
return =
(return){
line =
(RLine){
_uuid = "{1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF}"
pattern = "1018"
description = None
usage = "Device"
routePartitionName = ""
aarNeighborhoodName = ""
----Rest omitted for brevity---
Now, if I try to use pattern, not uuid, I have following error:
line6 = client.service.getLine({'pattern': '1018'}, {'routePartitionName': ''})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\suds\client.py", line 521, in __call__
return client.invoke(args, kwargs)
File "C:\Python27\lib\site-packages\suds\client.py", line 576, in invoke
soapenv = binding.get_message(self.method, args, kwargs)
File "C:\Python27\lib\site-packages\suds\bindings\binding.py", line 109, in get_message
content = self.bodycontent(method, args, kwargs)
File "C:\Python27\lib\site-packages\suds\bindings\document.py", line 95, in bodycontent
add_param, self.options().extraArgumentErrors)
File "C:\Python27\lib\site-packages\suds\argparser.py", line 83, in parse_args
return arg_parser(args, kwargs, extra_parameter_errors)
File "C:\Python27\lib\site-packages\suds\argparser.py", line 108, in __call__
self.__process_parameters()
File "C:\Python27\lib\site-packages\suds\argparser.py", line 299, in __process_parameters
self.__process_parameter(*pdef)
File "C:\Python27\lib\site-packages\suds\argparser.py", line 294, in __process_parameter
self.__in_choice_context(), value)
File "C:\Python27\lib\site-packages\suds\bindings\document.py", line 86, in add_param
p = self.mkparam(method, pdef, value)
File "C:\Python27\lib\site-packages\suds\bindings\document.py", line 130, in mkparam
return Binding.mkparam(self, method, pdef, object)
File "C:\Python27\lib\site-packages\suds\bindings\binding.py", line 225, in mkparam
return marshaller.process(content)
File "C:\Python27\lib\site-packages\suds\mx\core.py", line 59, in process
self.append(document, content)
File "C:\Python27\lib\site-packages\suds\mx\core.py", line 72, in append
self.appender.append(parent, content)
File "C:\Python27\lib\site-packages\suds\mx\appender.py", line 88, in append
appender.append(parent, content)
File "C:\Python27\lib\site-packages\suds\mx\appender.py", line 229, in append
Appender.append(self, child, cont)
File "C:\Python27\lib\site-packages\suds\mx\appender.py", line 168, in append
self.marshaller.append(parent, content)
File "C:\Python27\lib\site-packages\suds\mx\core.py", line 71, in append
if self.start(content):
File "C:\Python27\lib\site-packages\suds\mx\literal.py", line 86, in start
raise TypeNotFound(content.tag)
suds.TypeNotFound: Type not found: 'pattern'
Trying different syntax also gives error:
line6 = client.service.getLine('1018')
No handlers could be found for logger "suds.client"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\suds\client.py", line 521, in __call__
return client.invoke(args, kwargs)
File "C:\Python27\lib\site-packages\suds\client.py", line 581, in invoke
result = self.send(soapenv)
File "C:\Python27\lib\site-packages\suds\client.py", line 619, in send
description=tostr(e), original_soapenv=original_soapenv)
File "C:\Python27\lib\site-packages\suds\client.py", line 670, in process_reply
raise WebFault(fault, replyroot)
suds.WebFault: Server raised fault: 'Item not valid: The specified Line was not found'
Am I using incorrect syntax or it's actually not possible to use pattern however schema file states differently?
Additionally, I'm wondering how to extract only uuid value from for example listLine method, is it possible via python axl?
In Suds, if memory serves me correctly, you can use keyword arguments for get and update requests.
For example:
resp = client.service.getLine(routePartitionName='PT-ONCLUSTER', pattern='\+49301234567')
if that doesn't work, try:
resp = client.service.getLine({'routePartitionName': 'PT-ONCLUSTER', 'pattern': '\+49301234567'})
Or better yet, check out python-zeep instead. It's much faster and better maintained than suds. Some example code with Zeep:
# -*- coding: utf-8 -*-
from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
from zeep.exceptions import Fault
from zeep.plugins import HistoryPlugin
from requests import Session
from requests.auth import HTTPBasicAuth
from urllib3 import disable_warnings
from urllib3.exceptions import InsecureRequestWarning
from lxml import etree
disable_warnings(InsecureRequestWarning)
username = 'admin'
password = 'password'
# If you're not disabling SSL verification, host should be the FQDN of the server rather than IP
host = '10.1.1.1'
wsdl = 'file://C:/path/to/wsdl/AXLAPI.wsdl'
location = 'https://{host}:8443/axl/'.format(host=host)
binding = "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding"
# Create a custom session to disable Certificate verification.
# In production you shouldn't do this,
# but for testing it saves having to have the certificate in the trusted store.
session = Session()
session.verify = False
session.auth = HTTPBasicAuth(username, password)
transport = Transport(cache=SqliteCache(), session=session, timeout=20)
history = HistoryPlugin()
client = Client(wsdl=wsdl, transport=transport, plugins=[history])
service = client.create_service(binding, location)
def show_history():
for item in [history.last_sent, history.last_received]:
print(etree.tostring(item["envelope"], encoding="unicode", pretty_print=True))
try:
resp = service.getLine(pattern='1018', routePartitionName='')
except Fault:
show_history()

How to catch TimeoutError using Pulsar HttpClient with Tornado

I'm writing an app using Tornado. I need to make a lot of HTTP requests, but Tornado's HTTP client sucks a bit (doesn't have Keep-Alive support and is slow), so I'm trying to use Pulsar HttpClient:
import tornado.web
import tornado.gen
import tornado.httpserver
from tornado.platform.asyncio import AsyncIOMainLoop
from tornado.platform import asyncio as tornasync
import asyncio
from pulsar.apps import http as pulsar_http
class MyHandler(tornado.web.RequestHandler):
#tornado.gen.coroutine
def get(self):
http_client = self.application.http_client
future = tornasync.to_tornado_future(asyncio.async(http_client.request('GET', 'http://httpbin.org', timeout=.25)))
try:
result = yield future
except TimeoutError as e:
print('Timeout!')
print(result.get_content())
self.write('OK')
self.finish()
if __name__ == '__main__':
AsyncIOMainLoop().install()
app = tornado.web.Application([(r'/', MyHandler)], debug=False)
server = tornado.httpserver.HTTPServer(app)
server.bind(8888)
server.start(1)
app.http_client = pulsar_http.HttpClient(loop=asyncio.get_event_loop())
asyncio.get_event_loop().run_forever()
Bun when a timeout occurs, I get an exception:
Traceback (most recent call last):
File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/web.py", line 1415, in _execute
result = yield result
File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/gen.py", line 870, in run
value = future.result()
File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/concurrent.py", line 215, in result
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/gen.py", line 876, in run
yielded = self.gen.throw(*exc_info)
File "bpp.py", line 19, in get
result = yield future
File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/gen.py", line 870, in run
value = future.result()
File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/concurrent.py", line 215, in result
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
File "/usr/lib/python3.4/asyncio/tasks.py", line 300, in _step
result = coro.send(value)
File "/usr/lib/python3.4/asyncio/tasks.py", line 436, in wait_for
raise futures.TimeoutError()
concurrent.futures._base.TimeoutError
Can I catch this exception somehow?
Just import that error into your code:
from concurrent.futures import TimeoutError
Otherwise you can't catch it

Categories

Resources