Saravanan666/pypi-org huggingface dataset:
Package: nameko-http
nameko-httpHttp utilities for Nameko built-in HTTP extensionQuickstartInstall from pypi:$pipinstallnameko-httpExample:# helloworld.pyimportjsonfromwerkzeug.wrappersimportResponsefromnameko_httpimportapifromnameko_http.exceptionsimportHttpErrorclassHttpForbidden(HttpError):# Any Http Exceptions that are going to be raised need to inherit# from base exception class: HttpError.error_code='FORBIDDEN'status_code=403classExampleService:name="exampleservice"@api('GET','/privileged')defforbidden(self,request):raiseHttpForbidden('You shall not access')@api('GET','/foo',cors_enabled=True)defget_foo(self,request):returnResponse(json.dumps({'value':'foo'}),status=200,mimetype='application/json')$namekorunhelloworld
startingservices:exampleservice$curl-ilocalhost:8000/privileged
HTTP/1.1403FORBIDDEN
Content-Type:application/json
Content-Lentgh:61Date:Thu,01Nov201814:21:14GMT{"error_code":"FORBIDDEN","reason":"You shall not access"}curl-ilocalhost:8000/foo
HTTP/1.1200OK
Content-Type:application/json
Content-Length:16Access-Control-Allow-Origin:*
Access-Control-Allow-Headers:Authorization,Content-Type,Accept
Access-Control-Allow-Methods:OPTIONS,GET,POST,PUT,PATCH,DELETE
Access-Control-Allow-Credentials:falseDate:Thu,01Nov201814:23:21GMT{"value":"foo"}CreditsThis package was created with Cookiecutter_ and theaudreyr/cookiecutter-pypackage_ project template... _Cookiecutter:https://github.com/audreyr/cookiecutter.. _audreyr/cookiecutter-pypackage:https://github.com/audreyr/cookiecutter-pypackageHistory0.1.5 (2018-11-29)Fix for empty request body when request method POST, PUT or PATCH.0.1.4 (2018-11-20)Fix forhttps://discourse.nameko.io/t/webserver-can-be-subclassed-but-is-not-work-for-me/2660.1.3 (2018-11-05)fix bumping issue0.1.2 (2018-11-05)Pass cors headers when exceptionsAdded handling for expected exceptions0.1.1 (2018-11-01)Added utility method for making responsesREADME.md update with example usageDrop support for python:2.70.1.0 (2018-10-31)First release.
Package: nameko-keycloak
docstestspackageThis package is still work in progress.Helpers to integrate Single Sign-On innameko-based applications usingKeycloak.Featuresnameko service mixindatabase and model-agnostic user managementauthentication servicefake Keycloak client for use in testsInstallationpip install nameko-keycloakYou can also install the in-development version with:pip install https://github.com/emplocity/nameko-keycloak/archive/master.zipUsageTo set up SSO with Keycloak in your nameko service, follow these steps.Get Keycloak configuration from realm -> Clients -> Installation, download
as Keycloak OIDC JSON.NoteMake sureauth-server-urlends with a trailing slash.Save this configuration in a .json file.Add the mixin and dependency provider to your service and point to OIDC
JSON config:from nameko_keycloak.dependencies import KeycloakProvider
from nameko_keycloak.service import KeycloakSsoServiceMixin

class MyService(KeycloakSsoServiceMixin):
    keycloak = KeycloakProvider("/tmp/keycloak.json")Set up URLs for HTTP endpoints. The mixin exposes five methods prefixed
withkeycloak_, which you should use in your HTTP service.
Delegate from your entrypoints like this:@http("GET", "/login")
def login_sso(self, request):
    return self.keycloak_login_sso(request)This way it is up to you to control the URL routes and any middleware
or extra request handling (such as CORS headers).Implement afetch_user()method on your service that takes user’s
email address as a single argument and returns a user instance for that
email (orNoneif no such user exists in whatever storage you’re using).NoteWe assume that email address is unique for every user.For example:def fetch_user(self, email: str) -> Optional[User]:
    user_manager = UserManager(self.db.session)
    return user_manager.get_by_email(email)This method is used to ensure that there is a local application user who
matches the global identity stored in Keycloak.(Optionally) Implement success and failure hook methods on your service.If you providekeycloak_success()method, the mixin will call it after
successful login and redirect from Keycloak back to your application.
The method will receive currently logged user as its argument. Similarly
the mixin will callkeycloak_failure()upon Keycloak errors.Example:def keycloak_success(self, user: User) -> None:
    logger.info(f"Successful login: {user=}")

def keycloak_failure(self) -> None:
    logger.error("Failed to log in")NoteFailure hooks execute in a try/except block, so you can accesssys.exc_info, for example to capture exception to Sentry or other
error reporting tool.Documentationhttps://nameko-keycloak.readthedocs.io/Authorsnameko-keycloakis developed and maintained byEmplocity.LicenseThis work is released under the Apache 2.0 license.
Package: nameko-mongodb
OverviewThis is DependencyProvider forNameko microservices frameworkwhich
enables users to work with MongoDb.First of all I should say that this package based onhttps://github.com/saiqi/nameko-mongodb. Thank you @saiqi :)What has been changed:Automatic uploading to PyPI by Travis-CI (it was a primary purpose for building of my pet projects)Disabled by default results loggingSome fixes to make this stuff work with new NamekoRequirementsPython 2.7 / 3.4 / 3.5 / 3.6 / 3.7Nameko 3.11+MongoDb :)InstallationThe same as you guessing:pip install nameko-mongodbHow to useThere are some configuration options to use this package (required are in bold):MONGODB_CONNECTION_URL- connection URLMONGODB_DB_NAME - database name. Default is your service nameMONGODB_USER - if you need to be authenticated, provide usernameMONGODB_PASSWORDMONGODB_AUTHENTICATION_BASE - a source to authenticate. See more information inPyMongo documentationMONGODB_AUTH_MECHANISM - see more information inPyMongo documentationYou can use the connection following way:fromnameko.rpcimportrpcimportMongoDatabasefromnameko_mongodbclassYourService(object):name='your_service'database=MongoDatabase()@rpcdeffind_item(self):returnself.database.your_collection.find_one()Also this package can log all executions tologgingcollection. If you want to use it:fromnameko.rpcimportrpcimportMongoDatabasefromnameko_mongodbclassYourService(object):name='your_service'database=MongoDatabase(result_backend=True)@rpcdeffind_item(self):returnself.database.your_collection.find_one()Sometimes there can be useful to get possibility executing callbacks for DependencyProvider methods (i.e. migrating
data when dependency initialized etc.). There are some callbacks:on_before_setup: (instance)on_after_setup: (instance)on_before_stop: (instance)on_after_stop: (instance)on_before_worker_setup: (instance, worker_ctx)on_after_worker_setup: (instance, worker_ctx)on_before_worker_result: (instance, worker_ctx, result, exc_info)on_after_worker_result: (instance, worker_ctx, result, exc_info)How to use callbacks:fromnameko.rpcimportrpcimportMongoDatabasefromnameko_mongodbclassYourService(object):name='your_service'database=MongoDatabase(on_before_setup=lambdax:print("Start setup DP"),on_after_setup=lambdax:print("Stop setup DP"),)@rpcdeffind_item(self):returnself.database.your_collection.find_one()ContributionI'd be glad to see your pull requests
Package: nameko-mongoengine
nameko-mongoengineMongoEngine dependency provider forNamekomicroservice framework.Installationpipinstallnameko-mongoengineUsageThe basic usage of the dependency provider is shown:frommongoengineimportDocument,fieldsfromnameko_mongoengineimportMongoEnginefromnameko.rpcimportrpcclassMyModel(Document):"""My document model"""info=fields.StringField(required=True)classMockService:name="mock_service"engine=MongoEngine()@rpcdefwrite(self,info):model=MyModel()model.info=infomodel.save()returnmodel@rpcdefread(self,_id):returnMyModel.objects.get(id=_id)The dependencyengineexposes standardpymongointerface to database connections. The default connection can be accessed by thedbproperty:classMockService:name="mock_service"engine=MongoEngine()@rpcdefget(self,_id):returnself.engine.db.your_collection.find_one({'_id':_id})Other database connections defined byMongoEnginealiases can be accessed by:@rpcdefget(self,_id):db=self.engine.with_alias("your_alias").dbreturndb.your_collection.find_one({'_id':_id})ConfigurationsThe dependency configurations can be set in namekoconfig.yamlfile, or by environment variables.Config FileMONGODB_URI:mongodb://localhost:27017/dbname?replicaSet=replset# or# ---- with aliasesMONGODB_URI:default:mongodb://localhost:27017/dbname?replicaSet=replset"<alias>":"<uri>"Environment VariablesMONGODB_URI='mongodb://localhost:27017/dbname?replicaSet=replset'

# or
# ---- with aliases
MONGODB_URI='{"default": "mongodb://localhost:27017/dbname?replicaSet=replset", "<alias>": "<uri>"}'DevelopersTo perform development tasks and run tests run:$pipinstall-e.[dev]# to install all dependencies$dockerrun-d--restart=always--namesome-rabbit-p5672:5672-p15672:15672rabbitmq:3-management# Run rabbitmq-management server$dockerrun--rm-d-p27017:27017mongo# Run mongodb server on docker$pytest--cov=nameko_mongoenginetests/# to get coverage report$pylintnameko_mongoengine# to check code quality with PyLintOptionally you can usemake.ContributionsPull requests always welcomed. Thanks!
Package: nameko-objectstorage
nameko-objectstorage=================A IBM Bluemix Object Storage dependency for `nameko <http://nameko.readthedocs.org>`_, enabling services to interface with object storage containers and objects. Future improvements are full support for open stack object storage in general.Usage-----.. code-block:: pythonfrom nameko_objectstorage import ObjectStorageclass Service:storage = ObjectStorage()@event_handler("dispatcher", "topic")def handler(self, payload):obj = self.storage.get_object(container, object_name)# Do stuff with object...To-Do-----1. Write tests!2. Implement support for native open stack.
Package: namekoplus
namekoplusA lightweight Python distributed microservice solutionInstallationpython3-mpipinstallnamekoplusCLI UsageCheckout Commandnamekoplus--helpStart a middleware that nameko depends onnamekoplusstart-mrabbitmqInitialize a nameko service from templatesnamekoplusinit--directory<dir_name>--type<template_type>Detailed UsageSee Documents:English中文
Package: nameko-pony
nameko-ponyPony dependency for nameko servicesInstallationpip install nameko-ponyUsageapp.pyfromnameko.rpcimportrpcfrompony.ormimportDatabase,Requiredfromnameko_ponyimportPonySessiondb=Database()classPerson(db.Entity):name=Required(str)classFooService(object):name='foo_service'db_session=PonySession(db)@rpc@db_sessiondefhello(self):Person(name='hello')Person(name='world')@rpcdefworld(self):withself.db_session:return[p.nameforpinPerson.select()]config.ymlAMQP_URI: 'pyamqp://guest:guest@localhost'
DATABASE_URI: 'sqlite:///:memory:'
# DATABASE_URI: 'mysql://usr:pwd@localhost/db_name'
Package: nameko-prometheus
docstestspackagenameko-prometheusis a dependency for thenamekomicroservice framework
which allows application metrics collection withPrometheus.Featuresautomatic collection of request latency metrics for RPC methods, event
handlers and HTTP requestscustom application metrics are also exposed automaticallyHTTP endpoint exposing metrics to be scraped by PrometheusInstallationpip install nameko-prometheusYou can also install the in-development version with:pip install https://github.com/emplocity/nameko-prometheus/archive/master.zipUsageDefine your application metrics using types fromprometheus_client, such asCounter,Gauge,Histogram, etc. Add aPrometheusMetricsdependency provider to your service class. Then add a
HTTP entrypoint (usually routed under/metricsURL) that forwards the
request toexpose_metrics()method of the provider. That’s it!fromnameko.rpcimportrpcfromnameko.web.handlersimporthttpfromnameko_prometheusimportPrometheusMetricsfromprometheus_clientimportCounterwork_units=Counter("my_service_work_units_total","Total number of work units",["work_type"])classMyService:metrics=PrometheusMetrics()@rpcdefsay_hello(self):work_units.labels(work_type="hard").inc()return"Hello!"@http("GET","/metrics")defserve_metrics(self,request):returnself.metrics.expose_metrics(request)There are a few automatically defined metrics as well. See the documentation ofPrometheusMetricsfor more.See also the full stack example inexample/directory in this repo.Documentationhttps://nameko-prometheus.readthedocs.io/DevelopmentTo run the all tests run:toxNote, to combine the coverage data from all the tox environments run:Windowsset PYTEST_ADDOPTS=--cov-append
toxOtherPYTEST_ADDOPTS=--cov-append toxDevelopment roadmapThings we’d like to have in the future:automatic registration of/metricsHTTP endpointdecorator to exclude specific methods from tracingAuthorsnameko-prometheusis developed and maintained byEmplocity.LicenseThis work is released under the Apache 2.0 license.
Package: nameko-query
Namekoextension for support of running queries.Queries supports multiple replies for a single query sent and will be returned as a list.Examplesfromnameko_query.responderimportquery_responderclassBlockedListener(object):name="service"routing_prefix="service"@query_responderdefmethod(self,parameters,message):return"hello world"fromnameko_query.requestimportClusterQueryProxydefquery_request(service_name,method_name,parameters={}):withClusterQueryProxy({"AMQP_URI":"amqp://guest:guest@localhost",timeout=0.05)ascluster_query:service=getattr(cluster_query,service_name)method=getattr(service,method_name)returnmethod(parameters)printquery_request("service","method",parameters)
Package: nameko-salesforce
Nameko SalesforceANamekoextension with entrypoints for handlingSalesforce Streaming APIevents
and a dependency provider for easy communication withSalesforce REST API.The Streaming API extension is based onNameko Cometd Bayeux Clientand the REST API dependency
id based onSimple Salesforce.Quick StartInstall fromPyPI:pip install nameko-salesforceCreate a service which handles Salesforce Contact objects changes and also
has an RPC endpoint for creating new Contact objects in Salesforce:# service.pyfromnameko.rpcimportrpcfromnameko_salesforce.streamingimporthandle_sobject_notificationfromnameko_salesforce.apiimportSalesforceAPIclassService:name='some-service'salesforce=SalesforceAPI()@handle_sobject_notification('Contact',exclude_current_user=False)defhandle_contact_updates(self,sobject_type,record_type,notification):""" Handle Salesforce contacts updates
    """print(notification)@rpcdefcreate_contact(self,last_name,email_address):""" Create a contact in Salesforce
    """self.salesforce.Contact.create({'LastName':last_name,'Email':email_address})Create a config file with essential settings:# config.yamlAMQP_URI:'pyamqp://guest:guest@localhost'SALESFORCE:USERNAME:${SALESFORCE_USERNAME}PASSWORD:${SALESFORCE_PASSWORD}SECURITY_TOKEN:${SALESFORCE_SECURITY_TOKEN}SANDBOX:FalseRun the service providing your Salesforce credentials:$SALESFORCE_USERNAME=rocky\SALESFORCE_PASSWORD=***\SALESFORCE_SECURITY_TOKEN=***\namekorun--configconfig.yamlserviceFinally, open another shell and call the RPC endpoint to create a new user:$namekoshell--configconfig.yamlIn [1]: n.rpc['some-service'].create_contact('Yo', 'yo@yo.yo')You should see a new contact created in Salesforce and your service should
get a notification. In the first shell you’ll find the notification printed:{'event': {'replayId': 1, 'type': 'created' ...For more checkout thedocumentation.
Package: nameko-sematext-logger
Nameko Sematext LoggerGet Startedpip install nameko-sematext-loggerconfig.yamlSEMATEXT:
    KEY: ${SEMATEXT_KEY:<DEFAULT_KEY_HERE>}
    URL: <URL_HSER>
    PORT: 514service_file.pyfrom nameko_sematext import logger

class GreetingService:
    sematext_logger = logger.Sematext()

    ...
    def create_card(self, request):
        ...
        self.sematext_logger.critical('This is a critical log')
        self.sematext_logger.info('This is an info log')
        self.sematext_logger.warning('This is a warning log')
        self.sematext_logger.error('This is an error log')
        ...
Package: nameko-serializer
enhenced json serializer for nameko micro-services.it allow to passdatetime.dateanddatetime.datetimeto rpc calls and event arguments.
get ride ofdatetime.datetime not JSON serializableerrors messages in nameko.add support for namedtuple in service transmissions. you return a namedtuple instance,
you get the same namedtuple in the other side, which is retro-comatible and support eitherres.attrorres['attr']Stable branchDevelopment statusInstallationInstall using pip:pip installnameko-serializersAlternatively, you can download or clone this repo and install with :pip install-e..Requirementswork with nameko up to 1.12.*Examplesinstall:pip installnameko-serializersconfigure: add in your config.yaml the folowing line:serializer:nameko-serializerenjoydatetime support (with timezone)Documentationthis Readme is currently the full documentation. it’s not a library this big…featuresdate and datetime serializingthis serializer will handle datetime and date serializing. if a datetime is timezone naive, it will be made aware using
the detected current timezone (viatzlocal.get_localzone())all received dates will be timezone aware, but the timezone will be fixed to UTC.NamedTulpe supportthis serializer allow to transmit namedtuple as dict, and will deserialize it as special namedtuple, supporting dict indexRequirementsPython 2.7, 3.6, 3.7Notethis serializer use the builtin ordered dict feature to unserialize namedtuple with correct attributes order.
if you use python2.7 or 3.6 without cPython, you must exclusively use argument’s names and not indice.Contributions and pull requests are welcome.Bugs and requestsIf you found a bug or if you have a request for additional feature, please use the issue tracker on GitHub.https://github.com/Yupeek/nameko-serializer/issuesknown limitationsif you pass some objects with keys__type__, it will be converted.all unserialized dates will be tz aware, and tzinfo will be set to UTC. (this is a good practice to change tz at display time)for python < 3.7, the order in the namedtuple is not garanteed, use exclusively kwargs and attrs by namesLicenseYou can use this under GPLv3.AuthorOriginal author:Darius BERNARD.ThanksThanks to Nameko for this amazing framework.
Package: nameko-slackclient
Slack Extensions for NamekoNamekoextension for interaction withSlack APIs. UsesSlack Developer Kit for Python.Quick StartInstall fromPyPI:pip install nameko-slackclientReal Time Messaging Client“nameko>=2.7.0”, “slackclient>=2”The RTM extension is a Websocket client for Slack’sReal Time Messaging APIthat allows you to receive events from Slack in real time. Thertmmodule
contains two Nameko entrypoints for handling such events -handle_eventandhandle_message.UsageProvide Slack bot API token in your Nameko service config file:# config.ymlSLACK:TOKEN:"xoxb-abc-1232"Or using environment variable within your config:# config.ymlSLACK:TOKEN:${SLACK_BOT_TOKEN}More ExamplesListen for events of a particular type:fromnameko_slackclientimportrtmclassService:name='some-service'@rtm.handle_event('presence_change')defon_presence_change(self,event):passListen for any message type event:fromnameko_slackclientimportrtmclassService:name='some-service'@rtm.handle_messagedefon_any_message(self,event,message):passUse regular expressions to fire on matching messages only:fromnameko_slackclientimportrtmclassService:name='some-service'@rtm.handle_message('^spam')defon_message_starting_with(self,event,message):passParse message and pass matching groups as positional or named arguments
to the entrypoint:fromnameko_slackclientimportrtmclassService:name='some-service'@rtm.handle_message('^spam (\w*)')defon_spam(self,event,message,egg):pass@rtm.handle_message('^egg (?P<ham>\w+)')defon_egg(self,event,message,ham=None):passRespond back to the channel by returning a string in the message handling
entrypoint:fromnameko_slackclientimportrtmclassService:name='some-service'@rtm.handle_messagedefsure(self,event,message):return'sure,{}'.format(message)Run multiple RTM bots:# config.ymlSLACK:BOTS:alice:${ALICE_BOT_TOKEN}bob:${BOB_BOT_TOKEN}# service.pyfromnameko_slackclientimportrtmclassService:name='some-service'@rtm.handle_message(bot_name='alice')deflisten_as_alice(self,event,message):pass@rtm.handle_message(bot_name='bob')deflisten_as_bob(self,event,message):pass$ ALICE_BOT_TOKEN=xoxb-aaa-111 BOB_BOT_TOKEN=xoxb-bbb-222 nameko run --config ./config.yaml service
starting services: some-serviceWEB API ClientA simple dependency provider wrappingSlack WEB API client.UsageThe dependency provider uses the same config key as the RTM extension:# config.ymlAMQP_URI:'pyamqp://guest:guest@localhost'SLACK:TOKEN:${SLACK_BOT_TOKEN}# service.pyfromnameko.rpcimportrpcfromnameko_slackclientimportwebclassService:name='some-service'slack=web.Slack()@rpcdefsay_hello(self,name):self.slack.chat_postMessage(channel="#nameko",text="Hello from Nameko! :tada:")You can also use multiple bots:# config.ymlAMQP_URI:'pyamqp://guest:guest@localhost'SLACK:BOTS:alice:${ALICE_BOT_TOKEN}bob:${BOB_BOT_TOKEN}# service.pyfromnameko.rpcimportrpcfromnameko_slackclientimportwebclassService:name='some-service'alice=web.Slack('alice')bob=web.Slack('bob')@rpcdefsay_hello(self):self.alice.chat_postMessage(channel="#nameko",text="Hello from Alice! :tada:")self.bob.chat_postMessage(channel="#nameko",text="Hello from Bob! :tada:")
Package: nameko-stripe
nameko-stripeStripe dependency for NamekoRequirementsPython 3.4 - 3.7: Other versions may work but not supported.Installationpip install nameko-stripeUsagefromnameko.rpcimportrpcfromnameko_stripeimportStripeclassMyService(object):name="my_service"stripe=Stripe()@rpcdeflist_charges(self):returnself.stripe.Charge.list()SetupSimply add your api_key and log level into your config.yaml:AMQP_URI:'amqp://guest:guest@localhost'...STRIPE:api_key:abc123log_level:info
Package: nameko-structlog
Structlog as nameko extensionFree software: Apache Software License 2.0Extension fornamekothat replaces python logging module with structlog.
The idea behind this module is to useJSONRendererto be able to use advanced log aggregation and analysis tools likeLogstash.Apart from JSONRenderer structlog processor, it’s also supportedKeyValueRendererprocessor.InstallationTo install nameko-structlog, simply use pip.pipinstallnameko-structlogUsageAdd Structlog log level to your nameko config file:# config.yml when using JSONRendererSTRUCTLOG:INCLUDE_WORKER_NAME:${INCLUDE_WORKER_NAME:true}INCLUDE_LOG_TRANSACTON_ID:truePROCESSOR_NAME:JSONRendererPROCESSOR_OPTIONS:sort_keys:trueEXTRA_PARAMETERS:pin:1234env:devLOGGING:version:1formatters:simple:format:"%(message)s"handlers:console:class:logging.StreamHandlerformatter:simpleroot:level:DEBUGhandlers:[console]...OptionINCLUDE_WORKER_NAMEwill add or notworker_ctx.call_idto
every log entry. OptionINCLUDE_LOG_TRANSACTON_IDwill group all
logs that refer to same nameko entrypoint, with a uniquelog_transaction_id.
Doing so may be useful to follow request/data flow on a log aggregation
tool. OptionEXTRA_PARAMETERScan contain any keys that you
want to appear on every log entry.Include theStructlogDependencydependency in your service class:# service.pyfromnameko.rpcimportrpcfromnameko_structlogimportStructlogDependencyclassMyService(object):name="demo"log=StructlogDependency()@rpcdefmy_method(self,name):self.log.info(message=f"Your name is{name}",type="greeting")Run your service, providing the config file:$namekorunservice--configconfig.yaml$namekoshell--configconfig.yaml>>>n.rpc.demo.my_method("Alice"){"level":"info","log_transaction_id":"b2cd5506-339e-4e59-9a14-a3cd7548bfe5","logger":"demo","env":"dev",message": "YournameisAlice", "pin": "1234", "timestamp": "2020-09-27T11:24:30.379918Z", "type": "greeting"}CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.2.1 (2020-12-28)Fix bug#8.0.2.0 (2020-12-28)Dropindent=2for log recordsDropcoloramaanddevelopmentmode.Support two structlog processors,JSONRendererandKeyValueRenderer.Configuration is more clean now.Decouple Structlog configuration from nameko dependency.0.1.1 (2018-10-29)First release on PyPI.