Initializing 2 firebase apps in python - python

As part of my project, I've made 2 different Firestore databases. Usually, when I work with 1, it sets up fine in my project file. Now that I'm implementing BOTH of them in my python file (running discord.py), it throws up an error!
Here's the code for reference:
from firebase_admin import credentials, firestore, initialize_app
sccred = credentials.Certificate("scores-firebase.json")
scdefault_app = initialize_app(sccred)
scoredb = firestore.client(scdefault_app)
scdb = scoredb.collection('users')
stcred = credentials.Certificate("storage-firebase.json")
stdefault_app = initialize_app(stcred)
storagedb = firestore.client(stdefault_app)
stdb = storagedb.collection('january')
If I comment out the last 4 lines, it works fine, however, if I don't then the following error shows up:
Traceback (most recent call last):
File "main.py", line 51, in <module>
stdefault_app = initialize_app(stcred)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/firebase_admin/__init__.py", line 71, in initialize_app
raise ValueError((
ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.
I understood I need to add another argument, and I even went over the official firebase-admin docs for the package, yet I don't know how to add the required argument as there is no mention of it in the documentation.
Here's the documentation I referred to: https://firebase.google.com/docs/reference/admin/python/firebase_admin.db

You must specify a name for any Firebase Admin instances other than the default one:
# add the name param
stdefault_app = initialize_app(stcred, name='second_admin_instance')
Checkout the documentation for more information.

Related

Error when calling the Azure Quota SDK for python for Standard NCASv3_T4 Family types of instances

I have been trying to call the quota.get() method and it works for all resource names that doesn't have a space or underscore in the name, for example: "standardNCFamily" works but not for the rest like, "Standard NCASv3_T4 Family" does not.
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.quota import AzureQuotaExtensionAPI
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-quota
# USAGE
python quotas_list_quota_limits_for_compute.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = AzureQuotaExtensionAPI(
credential=DefaultAzureCredential(),
)
response = client.quota.list(
scope="subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.Compute/locations/eastus",
)
for item in response:
print(item)
# x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2021-03-15-preview/examples/getComputeQuotaLimits.json
if __name__ == "__main__":
main()
This is the sample code from samples repo in the Azure python github here
And this is the error I get when I call for the NCAS_v3 type of instances:
Traceback (most recent call last):
File "/Users/name/PycharmProjects/Virga-API/azure/trytry.py", line 35, in <module>
main()
File "/Users/name/PycharmProjects/Virga-API/azure/trytry.py", line 25, in main
response = client.quota.get(
File "/Users/name/PycharmProjects/Virga-API/venv/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "/Users/name/PycharmProjects/Virga-API/venv/lib/python3.10/site-packages/azure/mgmt/quota/operations/_quota_operations.py", line 237, in get
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
azure.core.exceptions.HttpResponseError: (InvalidResourceName) Name %60%60Standard%20NCASv3_T4%20Family%60%60 is not valid resource name.
Code: InvalidResourceName
Message: Name %60%60Standard%20NCASv3_T4%20Family%60%60 is not valid resource name.
I've been at it for hours trying different configurations for the names but can't seem to find it.
The documentation doesn't mention anything either.
Any help would be awesome!
It seems that your name contains underscores and spaces and you're accessing it in the wrong way without any casting and space safety resource, make sure that your resource name should match the name of the resource you want to retrieve information about, and it should be formatted correctly. For example, to retrieve information about Standard NCASv3_T4 Family instances, you should pass "Standard NCASv3_T4 Family" as your resource name to the quota.get() method, so your code should be like quota.get("Standard NCASv3_T4 Family") it should work anyway, if not, make sure you imported the correct resource type when calling the quota.get() method. The resource type you're using should match the type of that resource that you're trying to retrieve information about. For example, if you're trying to retrieve information about Standard NCASv3_T4 Family instances, you should use the resource type
"virtualMachineScaleSets" resource type, and also don't forget to check standard documentation they're always a good resource for everything!!

Pyramid fails to start when webtest and sqlalchemy are used together

I am trying to setup a pyramid app to use both webtest and sqlalchemy.
If I comment out the SQLAlchemy code, the webtests run without a problem.
[Test log ] https://travis-ci.org/caffeinated-expert/frisbee/builds/91622436
Error
Traceback (most recent call last):
File "frisbee/frisbee/tests/test_cities_page.py", line 18, in setUp
app = main({})
File "frisbee/frisbee/__init__.py", line 15, in main
engine = engine_from_config(settings, 'sqlalchemy.')
File "build/bdist.macosx-10.10-x86_64/egg/sqlalchemy/engine/__init__.py", line 426, in engine_from_config
url = options.pop('url')
KeyError: 'url'
In my main init file, if I comment out the sqlalchemy engine setup, then the tests run fine, but I need sqlalchemy for my project.
This is is the first time I have used webtest, so not sure if I have some other conflicting config.
[Failing code] https://github.com/caffeinated-expert/frisbee/commit/ea759015de755aca1d7bffca2845b72944572bed
From the sqlaclhemy docs:
The only required key is (assuming the default prefix) sqlalchemy.url
In your test_cities_page.py file you call main with an empty dictionary, presumably to be unpacked for **settings. You need to add the appropriate setting to the dictionary you're passing to the function and it should run. : )

Application ID error with GAE remote API

I am trying to use the Remote API in a local Client, following instructions given in Google documentation (https://developers.google.com/appengine/docs/python/tools/remoteapi).
I first tried from the Remote API shell, and everything is working fine. I can connect to my remote datastore and fetch data.
But when I run the following script, which is very similar to Google's example :
#!/opt/local/bin/python2.7
import sys
SDK_PATH = "/usr/local/google_appengine/"
sys.path.append(SDK_PATH)
import dev_appserver
dev_appserver.fix_sys_path()
from google.appengine.ext.remote_api import remote_api_stub
import model.account
def auth_func():
return ('myaccount', 'mypasswd')
remote_api_stub.ConfigureRemoteApi('myappid', '/_ah/remote_api', auth_func)
# Fetch some data
entries = model.account.list()
for a in entries:
print a.name
then I get an error :
Traceback (most recent call last):
File "./remote_script_test.py", line 26, in <module>
entries = model.account.list()
[...]
File "/Developer/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1333, in check_rpc_success
raise _ToDatastoreError(err)
google.appengine.api.datastore_errors.BadRequestError: Application Id (app) format is invalid: '_'
It says my application ID is a plain underscore '_', which is not the case since my app.yaml is correctly configured and when I do a
print app_identity.get_application_id()
from that script I get the correct application ID. I am under the impression that the GAE environment is not properly setup, but I could not figure out how to make it work. Does anyone have a full piece of code that works in this context ?
I am using Mac Os X Mountain Lion.
You may wish to start with remote_api_shell.py and remove stuff until it breaks, rather than add in things until it works.
For instance there's a line after the one you copied: remote_api_stub.MaybeInvokeAuthentication() is that necessary? There may be a number of necessary lines in remote_api_shell.py, maybe better to customize that rather than start from scratch.

Python suds error creating object

Trying to work with the echosign SOAP API.
The wsdl is here: https://secure.echosign.com/services/EchoSignDocumentService14?wsdl
When I try to create certain objects, it appears to not be able to find the type, even after listing it in print client
import suds
url = "https://secure.echosign.com/services/EchoSignDocumentService14?wsdl"
client = suds.client.Client(url)
print client
Service ( EchoSignDocumentService14 ) tns="http://api.echosign"
Prefixes (10)
ns0 = "http://api.echosign"
ns1 = "http://dto.api.echosign"
ns2 = "http://dto10.api.echosign"
ns3 = "http://dto11.api.echosign"
ns4 = "http://dto12.api.echosign"
ns5 = "http://dto13.api.echosign"
ns15 = "http://dto14.api.echosign"
ns16 = "http://dto7.api.echosign"
ns17 = "http://dto8.api.echosign"
ns18 = "http://dto9.api.echosign"
Ports (1):
(EchoSignDocumentService14HttpPort)
Methods (45):
...
Types (146):
ns1:CallbackInfo
ns17:WidgetCreationInfo
Trimmed for brevity, but showing the namespaces and the 2 types I'm concerned with right now.
Trying to run WCI = client.factory.create("ns17:WidgetCreationInfo") generates this error:
client.factory.create("ns17:WidgetCreationInfo")
Traceback (most recent call last):
File "", line 1, in
File "build/bdist.macosx-10.7-intel/egg/suds/client.py", line 244, in create
suds.BuildError:
An error occured while building a instance of (ns17:WidgetCreationInfo). As a result
the object you requested could not be constructed. It is recommended
that you construct the type manually using a Suds object.
Please open a ticket with a description of this error.
Reason: Type not found: '(CallbackInfo, http://dto.api.echosign, )'
So it doesn't appear to be able to find the CallbackInfo type. Maybe its because its missing the ns there?
Again, figured it out 15 min after posting here.
suds has an option to cross-pollinate all the namespaces so they all import each others schemas. autoblend can be set in the constructor or using the set_options method.
suds.client.Client(url, autoblend=True)
Take a look in the WSDL, it seems lots of definitions in http://*.api.echosign that suds cannot fetch.
Either update your /etc/hosts to make these not well-formed domains can be reached, or save the wsdl locally, modify it, then use Client('file://...', ...) to create your suds client.

Pyramid with memcached: how to make it work? Error - MissingCacheParameter: url is required

I have site on Pyramid framework and want to cache with memcached. For testing reasons I've used memory type caching and everything was OK. I'm using pyramid_beaker package.
Here is my previous code (working version).
In .ini file
cache.regions = day, hour, minute, second
cache.type = memory
cache.second.expire = 1
cache.minute.expire = 60
cache.hour.expire = 3600
cache.day.expire = 86400
In views.py:
from beaker.cache import cache_region
#cache_region('hour')
def get_popular_users():
#some code to work with db
return some_dict
The only .ini settings I've found in docs were about working with memory and file types of caching. But I need to work with memcached.
First of all I've installed package memcached from Ubuntu official repository and also python-memcached to my virtualenv.
In .ini file I've replaced cache.type = memory -> cache.type = memcached. And I've got next error:
beaker.exceptions.MissingCacheParameter
MissingCacheParameter: url is required
What am I doing wrong?
Thanks in advance!
So, using the TurboGears documentation as a guide, what settings do you have for the url?
[app:main]
beaker.cache.type = ext:memcached
beaker.cache.url = 127.0.0.1:11211
# you can also store sessions in memcached, should you wish
# beaker.session.type = ext:memcached
# beaker.session.url = 127.0.0.1:11211
It looks to me as if memcached requires a url to initialize correctly:
def __init__(self, namespace, url=None, data_dir=None, lock_dir=None, **params):
NamespaceManager.__init__(self, namespace)
if not url:
raise MissingCacheParameter("url is required")
I am not really sure why the code allows url to be optional (defaulting to None) and then requires it. I think it would have been simpler just to require the url as an argument.
Later: in response to your next question:
when I used cache.url I've got next error: AttributeError:
'MemcachedNamespaceManager' object has no attribute 'lock_dir'
I'd say that the way I read the code below, you have to provide either lock_dir or data_dir to initialize self.lock_dir:
if lock_dir:
self.lock_dir = lock_dir
elif data_dir:
self.lock_dir = data_dir + "/container_mcd_lock"
if self.lock_dir:
verify_directory(self.lock_dir)
You can replicate that exact error using this test code:
class Foo(object):
def __init__(self, lock_dir=None, data_dir=None):
if lock_dir:
self.lock_dir = lock_dir
elif data_dir:
self.lock_dir = data_dir + "/container_mcd_lock"
if self.lock_dir:
verify_directory(self.lock_dir)
f = Foo()
It turns out like this:
>>> f = Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in __init__
AttributeError: 'Foo' object has no attribute 'lock_dir'

Categories