Set/Get user information from a xmpp server: python - python

I am new in python and I am trying to create a testing python script to test different actions on my XMPP server. I already was able to test the login of my user and now I want to get the information that the server is sending (stanza) and set new information.
I have read several webs and I am not very clear with all this information. The main source has been sleekxmpp.com.
I have my stanza:
<iq type='get' to= 'chat.net' id='id1'>
<aa xmlns='http://myweb.com' />
</iq>
<iq type='result' to= 'chat.net' id='id1'>
<aa xmlns='http://myweb.com' >
<name>My name as included in sent mails<name>
<lang>en</lang>
<mail>My mail as included in sent mails</mail>
</aa>
</iq>
I want to get the information and also set one of the parameters (lets say name) but I don't know how.
class user_info(sleekxmpp.stanza.Iq):
self.get_query()
I must do it in python. Any help appreciated

What you want to do is create a custom stanza class for your stanza. Here's one that will work for the example you have:
from sleekxmpp import Iq
from sleekxmpp.xmlstream import ElementBase, register_stanza_plugin
class AA(ElementBase):
name = 'aa'
namespace = 'http://myweb.com'
plugin_attrib = 'aa'
interfaces = set(['name', 'lang', 'mail'])
sub_interfaces = interfaces
register_stanza_plugin(Iq, AA)
Ok, so what does all of that do? The name field specifies that the XML object's root tag is 'aa', and namespace specifies the root tag's namespace; obvious so far I hope.
The plugin_attrib field is the name that can be used to access this stanza from the parent stanza. For example, you should already be familiar with how you can use iq['type'] or iq['from'] to extract data out of an Iq stanza. With plugin_attrib set to "aa", then you can use iq['aa'] to get a reference to the AA content.
The interfaces set is the set of key names that this stanza provides for extracting information, just like working with dictionaries. For example an Iq stanza has 'to', 'from', 'type', etc in its interfaces set. By default, accessing and modifying these keys will create or modify attributes of the stanza's main element. So, at this point, your stanza would behave like this:
aa = AA()
aa['name'] = 'foo'
print aa
"<aa xmlns='http://myweb.com' name='foo' />"
Now, to instead map interface keys to subelements instead of attributes, they need to be in the sub_interfaces set. So by setting sub_interfaces = interfaces the above example would now work like so:
aa = AA()
aa['name'] = 'foo'
print aa
"<aa xmlns='http://myweb.com'><name>foo</name></aa>"
If you needed something more advanced, you could also define methods of the form get_* / set_* / del_* where * is the interface name which will then be used to extract or modify data.
So, all together, you will be able to do:
iq = Iq()
# ... set iq parameters
iq.enable('aa') # Add an initial, empty aa element.
try:
resp = iq.send()
print(resp['aa']['name'])
# ..., etc
except XMPPError:
print('There was an error')
Also, don't forget that we have the sleek#conference.jabber.org chat room for SleekXMPP help if you need it.

Related

How to differentiate using web3.py functions from a smart contract based on type/visibility?

I'm connecting to a smart contract with web3.py.
I am the contract owner connecting with the same address which deployed the contract.
I can print all functions, but I would like to separate each function based on their type and visibility, like read only or modify state, and visibility like: internal, external, public, etc.
Is there a way to do that with the web3.py library or any other library?
Here is my code:
# CONNECT TO CHAIN WITH WEB3
url = 'https://ropsten.infura.io/v3/e30d3bc3dfba4f92949b789dc797d82e'
w3 = Web3(Web3.HTTPProvider(url))
# CONNECT TO SMART CONTRACT
address = address_ABI.address # Importing from other file for more readability
abi = json.loads(address_ABI.abi) # Importing from other file for more readability
contract = w3.eth.contract(address=address, abi=abi)
# ACCOUNTS:
account_0 = wallets.account_0 # Importing from other file for more readability
private_key_0 = wallets.private_key_0 # Importing from other file for more readability
# LIST ALL CONTRACT FUNCTIONS
contract_functions = contract.all_functions() # Returns a list with all functions
print(len(contract_functions)) # Print number of functions
for function in contract_functions: # Print function one by one
print(function)
How do I print functions by different type and visibility? Like public, payable, read only, internal, external, etc?
I found a solution, not the most elegant, but working:
You can extract from the contract.abi all the elements and then call anything you want from the dictionary with the following: 'stateMutability'. this will return you the state, like: pure, view, non-payable, etc.
Here is a sample code:
for element in contract.abi:
if element['type'] == 'function':
print(element['name'], element['stateMutability'])
else:
pass
You can also extract other types, like "event' instead of 'function'. Hope this helps.

Extract data from notion using python

I'm using Notion to store my data {client name, subscription...} in tables.
I want to extract some data using python but I can't figure out how.
For example count the total number of clients, get the total amount of subscriptions...
Could you please suggest a way to help me.
If you need to do this only once - you can export a notion page (database) to HTML, which will probably be easier to extract from.
If you want this as a weekly/daily/monthly thing - I can't help with doing that in python but zapier and automate.io would be perfect.
For fetching the data you can use notion-client. The great thing about it is that it supports both sync and async interfaces. What it lacks, though, is an easy way to navigate the data's structure (which is quite complicated in Notion)
For that you can use basic-notion. It allows you to use model classes to easily access all the properties and attributes of your Notion objects - kind of like you would with an ORM.
In your case the code might look something like this:
from notion_client import Client
from basic_notion.query import Query
from basic_notion.page import NotionPage, NotionPageList
from basic_notion.field import SelectField, TitleField, NumberField
# First define models
class MyRow(NotionPage):
name = TitleField(property_name='Name')
subscription = SelectField(property_name='Subscription')
some_number = NumberField(property_name='Some Number')
# ... your other fields go here
# See your database's schema and the available field classes
# in basic_notion.field to define this correctly.
class MyData(NotionPageList[MyRow]):
ITEM_CLS = MyRow
# You need to create an integration and get an API token from Notion:
NOTION_TOKEN = '<your-notion-api-token>'
DATABASE_ID = '<your-database-ID>'
# Now you can fetch the data
def get_data(database_id: str) -> MyData:
client = Client(auth=NOTION_TOKEN)
data = client.databases.query(
**Query(database_id=database_id).filter(
# Some filter here
MyRow.name.filter.starts_with('John')
).sorts(
# You can sort it here
MyRow.name.sort.ascending
).serialize()
)
return MyData(data=data)
my_data = get_data()
for row in my_data.items():
print(f'{row.name.get_text()} - {row.some_number.number}')
# Do whatever else you may need to do
For more info, examples and docs see:
notion-client: https://github.com/ramnes/notion-sdk-py
basic-notion: https://github.com/altvod/basic-notion
Notion API Reference: https://developers.notion.com/reference/intro

Check for particular value from class object and get the value of another key

I have code implemented to reach the DB using CLI client.
I can be able to get the values as needed.
Consider the following code:
# Establish the connection Cloudkitty
ck = client.get_client(kwargs_conn.get('cloudkitty_version'), **kwargs_conn)
list_services = ck.hashmap.services.list()
for services in list_services:
print services
print(type(services))
It will produce the output as follows:
<hashmap.Service {u'service_id': u'2c6e0447-0cdb-4d12-8511-4544ba0d03b5', u'name': u'compute'}>
<class 'cloudkittyclient.v1.rating.hashmap.Service'>
<hashmap.Service {u'service_id': u'48297131-de33-48ad-b5b5-43d3a3177841', u'name': u'volume'}>
<class 'cloudkittyclient.v1.rating.hashmap.Service'>
Output being retuned is used to be a class object.
Now here I need to check for the returned object for particular value for the key. To be precise I want to check that whether it have the 'name' as 'compute', If yes I need to get the service_id of the same.
Someone let me know how we can achieve the same.
Library used : https://github.com/openstack/python-cloudkittyclient
Looking at some of tests in the library, it seems you can directly access the fields like service_id:
for service in list_services:
if service.name == 'compute':
print(service.service_id)
Or, if you want to get the service ids for all the services where name is compute:
service_ids = [service.service_id for service in list_services if service.name == 'compute']
if services.get("name") == "compute":
id_ = services.get("service_id")
#assuming li = [] declaration above you could add that to a list
# of IDs
li.append(id_)
Note I am assuming from the prints above that the class is Dictionary-like in behavior.

How to get SessionID in QuickFix

I am using QuickFix with Python. On the back of this question, I've explored the SessionID class a bit, but I am mystified by the behavior.
The SessionID class is described here. It is formed of a BeginString, SenderCompID and TargetCompID.
Say my SessionID in string form looks like this: FIX.4.2:LMXTS->TS68.
fix.SessionID().fromString() returns :->
Which if you look, are the three filler characters separating the BeginString, SenderCompID and TargetCompID.
fix.SessionID().getBeginString returns 8=☺ (i.e. the BeginString is nowhere). And the same thing applies to getSenderCompID and getTargetCompID, they return 49=☺ and 56=☺ respectively.
fix.SessionID().getTargetCompID().getValue() returns the empty string ''.
Trying another way, fix.SessionID().fromString('FIX.4.2:LMXTS->TS68') returns None.
I am trying to get these values after the session is created (which I can explicitly see happening when I pass fix.ScreenLogFactory(settings) to the initiator. So I am confused.
The method void onLogon( const SessionID& ) {} in Application.h is fired when the session is logged on, and gives you a reference to a SessionID. You could inspect the SessionID object inside onLogon to see how it behaves.
you can do it any of the quickfix methods after your session is created as the sesionId is one of the parameters.
The first method fired is onCreate so you can potentially store the sesionId in your class var and then reuse if if and when required to retrieve your settings. You can also use the onLogon method as suggested in one of the other answers.
Example below
def onCreate(self, sessionID):
self.session_id = sessionID
target = sessionID.getTargetCompID().getString()
sender = sessionID.getSenderCompID().getString()
It sounds like you're looking at the session directly after creating it, before logging on etc. So that means you're not using a breakpoint in, say, FromApp or ToApp to look at the session properties there. If you do, you get the properties directly i.e. SenderCompID, or TargetCompID.
I cannot find the method SessionID in the objects I use. How do you define your 'fix' object?

Making google analytics ID a variable

My app serves multiple domains which I understand should be done by namespaces which I'm researching. Since multiple domains should have multiple analytics ID:s I get the analytics ID from the code but I want to make it even more configurable:
if os.environ.get('HTTP_HOST').endswith('.br') \
or os.environ['SERVER_NAME'].endswith('.br'):
data[u'analytics'] = 'UA-637933-12'
else:
data[u'analytics'] = 'UA-637933-18'
self.response.out.write(template.render(os.path.join(os.path.dirname(__file__),
'templates', name + '.html'), data))
The above sets analytics ID to ..-12 if it's my brazilian domain and to the other ID ...-18 if it is my dot com. But this is only for 2 domains and it's not easiliy generalizable. How can I achieve this function in a more scientific and scalable way so that it becomes easy to add my application to a domain without manually adding the domain to my application?
I suppose namespaces is the way to go here since the domains are google apps domains but I don't understand how to use namespaces:
def namespace_manager_default_namespace_for_request():
"""Determine which namespace is to be used for a request.
The value of _NAMESPACE_PICKER has the following effects:
If _USE_SERVER_NAME, we read server name
foo.guestbook-isv.appspot.com and set the namespace.
If _USE_GOOGLE_APPS_DOMAIN, we allow the namespace manager to infer
the namespace from the request.
If _USE_COOKIE, then the ISV might have a gateway page that sets a
cookie called 'namespace', and we set the namespace to the cookie's value
"""
name = None
if _NAMESPACE_PICKER == _USE_SERVER_NAME:
name = os.environ['SERVER_NAME']
elif _NAMESPACE_PICKER == _USE_GOOGLE_APPS_DOMAIN:
name = namespace_manager.google_apps_namespace()
elif _NAMESPACE_PICKER == _USE_COOKIE:
cookies = os.environ.get('HTTP_COOKIE', None)
if cookies:
name = Cookie.BaseCookie(cookies).get('namespace')
return name
I suppose I should use the namespace manager, get the namespace and set the analytics ID according to the namespace but how?
Thank you
The simplest way to do this is with a Python dict:
analytics_ids = {
'mydomain.br': 'UA-637933-12',
'mydomain.com': 'UA-637933-18',
}
data['analytics'] = analytics_ids[self.request.host]
If you have other per-domain stats, you may want to make each dictionary entry a tuple, a nested dict, or a configuration object of some sort, then fetch and store it against the current request for easy reference.
If you want to be able to reconfigure this at runtime, you could use a datastore model, but that will impose extra latency on requests that need to fetch it; it seems likely to me that redeploying each time you add a domain isn't likely to be a problem in your case.
Namespaces are tangential to what you're doing. They're a good way to divide up the rest of your data between different domains, but they're not useful for dividing up configuration data.
I presume you have two instances of the same application running.
Instead of fiddling with namespaces, I suggest you turn the Analytics ID into a configuration variable.
That is, either store it in a config file or a database your web is using. Then set one ID for each deployment (in each place your web is running from) and fetch it in the runtime.
For example:
Config file:
analyticsId="UA-637933-12"
Code:
data[u'analytics'] = getValueFromConfig("analyticsId")
where getValueFromConfig is a function you define to read the appropriate value. (To use configuration files effortlessly, you may use the ConfigParser module.)
Now you've gained a lot more flexibility - you don't have to do any checking and switching at runtime. You only have to define the value once per web site and be done with it.

Categories

Resources