How to increment values in firebase realtime database python? - python

I have the exact same question as this one but in python :
How to increment values in Firebase Realtime Database (v9)
Is it actually implemented or not ? Because i am unable to find how to perform a :
from firebase_admin import db
realtime_db = db.reference(path="/", app=app, url="myurl")
realtime_db.update({
f"chats/{uid}/num": db.increment(1),
})
Thanks in advance

From looking at the documentation of the Python Admin SDK there doesn't seem to be an implementation of the increment operation there.
Luckily, that operation just gives you a sentinel value to send to the server, and you can create that yourself too based on the example in the documentation for the REST API. It should be something like this:
realtime_db.update({
f"chats/{uid}/num": { ".sv": { "increment": 1 }},
})
Syntax errors in the above example are definitely possible, so let me know about any of those you encounter and fix below please.

Related

GET and POST Function App Function/Host Keys Using Python (Azure Government)

I am attempting to retrieve and add function/host keys for an Azure Government function app via Python. I am currently working with the information from this question and the corresponding API page. While these are not specific to Azure Government, I would think the process would be similar after updating the URLs to the Azure Government versions. However, I am receiving the error "No route registered for '/api/functions/admin/token'" when running the jwt part of the given code. Is this approach feasible for what I am trying to do?
I also found somewhere that I instead might want to try a GET request like this:
resp = requests.get("https://management.usgovcloudapi.net/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Web/sites/<function-app-name>/functions/admin/masterkey?api-version=20XX-XX-XX", headers={"Authorization": f"Bearer {something}"})
This gives me the error "{"error":{"code":"InvalidAuthenticationToken","message":"The access token is invalid."}}", though. If this is indeed the correct approach, then what format should the Bearer token take?
Bit late answering but it may be useful for someone else in the future, it took me a while to find out how to do this.
If you want to retrieve the keys of a specific function within a function app then you can use list_function_keys() function from the Python SDK
Working with the Az management API directly may be a bit annoying and since the Azure CLI is written in Python whatever operation you do with the CLI you can do it directly in a Python script.
Here's an example of how you can retrieve the keys
from azure.identity import DefaultAzureCredential
from azure.mgmt.web import WebSiteManagementClient
# Your subscription ID
SUB_ID = "00000000-0000-0000-0000-000000000000"
fn_name = "some_function" # Name of your function
app_name = "some_app" # Name of your site/function app
rg_name = "some_rg" # Resource group name to which the function belongs
web_client = WebSiteManagementClient(subscription_id=SUB_ID, credential=DefaultAzureCredential())
keys = web_client.web_apps.list_function_keys(rg_name, app_name, fn_name)
# Your keys will be accessible in the additional_properties param
print(keys.additional_properties)
Hope it helps! I'm new on Azure so if I'm doing something wrong, please don't hesitate to point out my mistake and share your correction

Why python posting one data will appear 6 times on Firebase database

I just use the simple code to post a data to firebase, but I don't know why it appears 6 times on firebase realtime database.
from firebase import firebase
url = "https://xxx.firebaseio.com/"
fb = firebase.FirebaseApplication(url, None)
fb.post("/posts", {'ID':123})
I run "python fb.py" one time only.
However the result is:
I am very confused.
Are you trying to update this field or create a new entry with a unique ID when you run your code?
Maybe try using fb.put() instead.
fb.post() is the equivalent of .push() in the JavaScript API, so it creates a unique ID for you. fb.put() is equivalent to .set() and will just set the data.

Mongodb: Getting upsert result in pymongo

Mongo returns a WriteResult on upserts:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Is there any way I could access those fields from pymongo? I need this because an update always returns none in pymongo and I want to know if the document I was querying was modified or even if it exists without doing an additional query. Can you please tell me how this could be done?
P.S. I know this has been asked before but it was a few years ago and everything I could found on google didn't include an example.
Since we're at it, is there a way to get fields from the document from the result of an upsert? (or at least the _id)
Solved: As Neil Lunn suggests, the Bulk API is the way to go if you want to get more data out of what happened with your updates. I'd just like to point out this quick walkthrough of the API.
The newer MongoDB shell implementations from MongoDB 2.6 and upwards actually define there shell helper methods for .update() and .insert() etc, using the "Bulk operations API" where this is available.
So basically where the shell is connecting to a a MongoDB 2.6 instance or greater the "Bulk" methods are used "under the hood". Even if they actually are only acting on one document at a time, or otherwise effectively only issuing "one" update request or similar.
The general driver interfaces have not yet caught up with this and you need to still invoke explicitly:
bulk = db.test.initialize_ordered_bulk_op()
bulk.find({}).upsert().update({ "$set" { "this": "that" } }
result = bulk.execute()
The "result" returned here matches the "Bulk Write Result" specification you see in the shell, which is different to how the "legacy" implementations which are currently used in the standard driver methods return.

Setting up a Python ViewServer for CouchDB

I am trying to get up to speed with CouchDB. As a relatively new user on Python, I am trying to set up a view-server so that I can pass on python functions to couchdb.design.ViewDefinitions function. As I understand, ViewDefinitions take javascript code to execute map/reduce function.
Here is what I struggle to understand - I am well aware that this might be a basic question. According to wiki (http://wiki.apache.org/couchdb/View_server):
To register query servers with CouchDB, add a line for each server to local.ini. The basic syntax is:
'[query_servers] python=/usr/bin/couchpy'
How do I access local.ini file? I am an 10.6.8 Mac user. Thanks!
Update: Thank you Kxepal. It seems I was able to create the design/view on Futon in Python. Alternatively, I figured that python viewserver can be created as follows:
curl -X PUT http://[localhost]/_config/query_servers/python '"/path/to/couchpy"'
However, I still cannot execute the python script. Running the view on Couch results in following:
'Error: An error occurred accessing the view no response'
I would appreciate if somebody can point in the right direction. Thanks!
I encountered the same "Error: An error occurred accessing the view no response" problem, and it turned out to be a bug in my python code. Specifically, in the javascript implementation I had something like:
function (doc) {
emit(doc.somefield, doc);
}
I had converted this to:
def map(doc):
yield doc.somefield, doc
However, this gave me the "no response" error you describe.
Changing it to the following fixed the problem.
def map(doc):
yield doc['somefield'], doc
I don't know there OSX keeps CouchDB config files, but you always may setup Python query server through Futon. On sidebar click Configuration, than "Add section" at the bottom of the page and fill the fields with same data as you planned to write into local.ini. As bonus, you don't need restart CouchDB - configuration changes through HTTP API are applied instantly, but be sure that you'd specified correct values.

Creating Database for ios

I'm creating an app in which database will be updated via server, or it should be replaced by new one. Can you give me some tips, should I use CoreData or SqlLite. And how it should be updated. I'm using python for parsing data, and then I want to create DB.
Thank you!
This question is not very specific, but if you are not sure what you really need, stay away from CoreData. Start with SQLite and maybe use a light wrapper on top of it. I personally use FMDB.
There are quite a few examples in FMDB on how to select, insert, update etc. Quick example select from the Executing Queries section of the readme:
FMDatabase *db = [FMDatabase databaseWithPath:#"/tmp/tmp.db"];
FMResultSet *s = [db executeQuery:#"SELECT * FROM myTable"];
while ([s next]) {
//retrieve values for each record
}

Categories