Python Pyrebase Config - python

When I'm trying to run my code:
import pyrebase
firebaseConfig = {
"apiKey": "xxxxxx",
"authDomain": "xxxxxx",
"projectId": "xxxxxx",
"storageBucket": "xxxxxxx",
"serviceAccount": "xxxxxxxxx"
}
firebase_storage = pyrebase.initialize_app(firebaseConfig)
storage = firebase_storage.storage()
storage.child("uploads").put("xxxxxxx")
I'm getting an error:
self.database_url = config["databaseURL"]
KeyError: 'databaseURL'
I don't know what to do. Can someone help me?

When you create a new Firebase project it no longer creates a Realtime Database by default. And that also means that the databaseURL key is no longer included in the configuration snippet by default.
It looks like Pyrebase still requires this key to exist though, which is why you get an error.
Two things to try (in this order):
Just add a key with no value, or a dummy value to the firebaseConfig:
firebaseConfig = {
"apiKey": "xxxxxx",
"authDomain": "xxxxxx",
"databaseURL": "xxxxxx",
"projectId": "xxxxxx",
"storageBucket": "xxxxxxx",
"serviceAccount": "xxxxxxxxx"
}
If the above doesn't work, you can create a Realtime Database in the Firebase console, and get the new config snippet from there.
I also filed an issue against Pyrebase to no longer require this key, which is what all official Firebase SDKs have been updated to do.

Add
"databaseURL" : ""
in firebaseConfig (if you are not using database).

You need to add databaseURL key to your configurations.
Please take a look at this answer:
KeyError: 'databaseURL' while Firebase Authentication in Python

import pyrebase
config ={
"apiKey": "*********",
"authDomain": "***-****.firebaseapp.com",
"projectId": "****-*****",
"storageBucket": "****-***.appspot.com",
"messagingSenderId": "********",
"appId": "1:********:web:*********",
"measurementId": "G-*********",
"databaseURL" : ""
}
firebase = pyrebase.initialize_app(config)
storage = firebase.storage()
storage.child("download1.png").put("download.png")
Rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}

Related

Updating Azure Container Registry Public Access IP with Python

I've tried looking online but could not find an answer as the documentation (and the API) for Azure Python SDK is just horrible.
I have a Container Registery on Azure with a list of allowed IPs for public access. I'd like to modify that list by adding a new IP using Python.
I'm not sure the API supports it or how to achieve this using ContainerRegistryManagementClient.
Can't agree more that documentation (and the API) for Azure Python SDK is just horrible :)
If you want to add a list of allowed IPs for public access to your Container Registery on Azure, just try the code below using REST API:
from azure.identity import ClientSecretCredential
import requests
TENANT_ID= ""
CLIENT_ID = ""
CLIENT_SECRET = ""
SUBSCRIPTION_ID = ""
GROUP_NAME = ""
REGISTRIES = ""
#your public ip list here
ALLOWED_IPS = [{
"value": "167.220.255.1"
},
{
"value": "167.220.255.2"
}
]
clientCred = ClientSecretCredential(TENANT_ID,CLIENT_ID,CLIENT_SECRET)
authResp = clientCred.get_token("https://management.azure.com/.default")
requestURL = 'https://management.azure.com/subscriptions/'+SUBSCRIPTION_ID+'/resourceGroups/'+GROUP_NAME+'/providers/Microsoft.ContainerRegistry/registries/'+REGISTRIES+'?api-version=2020-11-01-preview'
requestBody = {
"properties": {
"publicNetworkAccess": "Enabled",
"networkRuleSet": {
"defaultAction": "Deny",
"virtualNetworkRules": [],
"ipRules": ALLOWED_IPS
},
"networkRuleBypassOptions": "AzureServices"
}
}
r = requests.patch(url=requestURL,json=requestBody,headers={"Authorization":"Bearer "+ authResp.token})
print(r.text)
Result:
Before you run this, pls make sure that your client app has been granted the required permissions(Azure subscription roles, such as contributor).

read only firebase storage rules tab

I would like to set the rules tab of my firebase object to read only.
When I take off the write parcel I got an error on my python when trying to add files to my storage.
Below is my code
import firebase_admin
config={
"apiKey": "xxx",
"authDomain": "xxx",
"databaseURL": "xxx",
"projectId": "xxx",
"storageBucket": "xxx",
"messagingSenderId": "xxx",
"appId": "xxx",
"measurementId": "xxx"
}
# Initialize connection to firebase_admin
firebase = firebase_admin.initialize_app(config)
storage = firebase.storage()
path_on_cloud ="Data quality report/Data quality report.py"
path_local = "Data_quality_report.py"
storage.child(path_on_cloud).put(path_local)
My rules tab is
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read;
allow write: if request.auth != null;
}
}
}
Do you guys know how to fix this problem?
Thank you in advance
Don't initialize it that way!
You are using the firebase_admin package which using the Firebase Admin SDK. To initialize it create a new service account key file which is then used for initializing.
Admin does what it sounds like it would do. It has all privileges.
Refer the official docs for proper explanation on setup. (I am really bad at explaining things).
https://firebase.google.com/docs/storage/admin/start#python

no supported Swagger or OpenAPI version field for flask_swagger_ui

I use flask_swagger_ui to add "Swagger UI" to my application, but when I launche it I receive this error:
Unable to render this definition The provided definition does not
specify a valid version field.
Please indicate a valid Swagger or OpenAPI version field. Supported
version fields are swagger: "2.0" and those that match openapi: 3.0.n
(for example, openapi: 3.0.0).
swagger specific
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'
SWAGGER_UI_BLUEPRINT = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={
'app_name': "my_application"
}
)
app.register_blueprint(SWAGGER_UI_BLUEPRINT, url_prefix=SWAGGER_URL)
/static/swagger.json
{
"info": {
"description": "this is swagger application",
"version": "1.0.0",
"title": "swagger-application",
"contact": {
"email": "zouhair11elhadi#gmail.com"
},
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
},
"swagger": "2.0",
"paths": {}
}
Solved
the problem comes from my browser (or else from the hidden memory of my browser), when I refresh it, it does not download the new modifications.
so to fix this problem follow this wiki

Google Cloud - Invalid JSON payload received. Unknown name "encoding" at 'config': Proto field is not repeating, cannot start list

When I try to invoke Google Cloud Speech to Text Api for long-running recognition with the following config:
config = dict(
languageCode='de',
maxAlternatives=1,
enableWordTimeOffsets=True,
enableAutomaticPunctuation=True,
model='default',
encoding='ENCODING_UNSPECIFIED'
)
I get this error
Invalid JSON payload received. Unknown name "encoding" at 'config': Proto field is not repeating, cannot start list
How to fix it?
Could you please give us some more information... like which language and library version you are using for this part of your project?
Assuming you are using Python, you could find another official way for connecting to Google Cloud Speech to Text Api here: https://cloud.google.com/speech-to-text/docs/basics
The way I am used to do is by using googleapiclient phyton package alongside with JSON data structure instead of dictionary data.
import base64
import googleapiclient.discovery
with open(speech_file, 'rb') as speech:
# Base64 encode the binary audio file for inclusion in the JSON
# request.
speech_content = base64.b64encode(speech.read())
# Construct the request
service = googleapiclient.discovery.build('speech', 'v1')
service_request = service.speech().recognize(
body={
"config": {
"encoding": "LINEAR16", # raw 16-bit signed LE samples
"sampleRateHertz": 16000, # 16 khz
"languageCode": "en-US", # a BCP-47 language tag
},
"audio": {
"content": speech_content
}
})
Refer to this official article if you don't know how to install python packages: https://packaging.python.org/tutorials/installing-packages/#id13
For LongRunning requests, please refer to:
https://cloud.google.com/speech-to-text/docs/reference/rest/v1/speech/longrunningrecognize
The config JSON structure in this case will be:
{
"config": {
object(RecognitionConfig)
},
"audio": {
object(RecognitionAudio)
}
}
Where RecognitionConfig is a JSON object of the kind:
{
"encoding": enum(AudioEncoding),
"sampleRateHertz": number,
"languageCode": string,
"maxAlternatives": number,
"profanityFilter": boolean,
"speechContexts": [
{
object(SpeechContext)
}
],
"enableWordTimeOffsets": boolean
}
And RecognitionAudio is of the kind:
{
// Union field audio_source can be only one of the following:
"content": string,
"uri": string
// End of list of possible types for union field audio_source.
}
For LongRunning recognition, you may also refer to this link:
https://developers.google.com/resources/api-libraries/documentation/speech/v1/java/latest/com/google/api/services/speech/v1/Speech.SpeechOperations.html
It shows how to use the Phyton package googleapiclient.discovery for long running requests, which is just by using the following method in your Phyton class:
...
service_request = service.speech().longrunningrecognize(
body= {
"config": {
"encoding": "FLAC",
"languageCode": "en-US",
"enableWordTimeOffsets": True
},
"audio": {
"uri": str('gs://speech-clips/'+self.audio_fqid)
}
}
)
...

Pyrebase apikey not defined error

import pyrebase
config = {
apiKey: "xxxxxxxxxxxxxxxxx",
authDomain: "lab-marks.firebaseapp.com",
databaseURL: "https://lab-marks.firebaseio.com",
projectId: "lab-marks",
storageBucket: "lab-marks.appspot.com",
messagingSenderId: "9983241061112"
}
firebase=pyrebase.initialize_app(config)
db=firebase.database()
users=db.child('users').get()
print(users.val())
I am integrating python with firebase.But while I run this code I get an NameError, showing that apikey not defined.
apiKey: "xxxxxxxxxxxxxxxxxxxxx",
NameError: name 'apiKey' is not defined
I had the same problem.
You must make the keys in the dictionary config in quotes and then everything will work fine.
P.S: Do not forget to put in quotes and other keys.
For example:
config = {
"apiKey": "xxxxxxxxxxxxxxxxx",
"authDomain": "lab-marks.firebaseapp.com",
"databaseURL": "https://lab-marks.firebaseio.com",
"projectId": "lab-marks",
"storageBucket": "lab-marks.appspot.com",
"messagingSenderId": "9983241061112"
}

Categories

Resources