read only firebase storage rules tab - python

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

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).

Python Pyrebase Config

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;
}
}
}

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)
}
}
)
...

Deploy App Engine version from Python with service account

Trying to deploy an App Engine instance from Python by using service account. The goal is to spin up a lot of instances, do some heavy network task (download and upload files) and shut them down afterwords.
I'm trying to do it with service account from Python runtime, but getting the following error
TypeError: Missing required parameter "servicesId"
What could be wrong or is there a better solution for such task? Thanks and the code is below:
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'service.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
gcp = build('appengine', 'v1', credentials=credentials)
res = gcp.apps().create(body={"id":"251499913983"})
app_json = {
"deployment": {
"files": {
"my-resource-file1": {
"sourceUrl": "https://storage.googleapis.com/downloader_sources/hello-world/main.py"
}
}
},
"handlers": [
{
"script": {
"scriptPath": "main.app"
},
"urlRegex": "/.*"
}
],
"runtime": "python27",
"threadsafe": True
}
res2 = gcp.apps().services().versions().create(body=app_json)
I guess you need to specify the service you want to deploy to. You could use default:
gcp.apps().services().versions().create(serviceID=default, body=app_json)
See doc for more details.

Login to Instagram and follow one account

I want to give 10 complimentary followers to the users who enter their Instagram username on my website.
I have pre-registered 10 Instagram profiles for this. ( E.g. IGprofile1, Igprofile2...Igprofile10).
When a user enters his username (E.g. kimkardashian) on the form and click submit, it'll be sent to my web server and give 10 followers to "kimkardashian"
IGprofile1-->login-->follow "kimkardashian" -->logout
IGprofile2-->login-->follow "kimkardashian" -->logout
....
....
IGprofile10-->login-->follow "kimkardashian" -->logout
I need this to on my server.
Below is a code one of my friend gave me
Any expert idea will be greatly appreciated.
.
"""
Follow
"""
import argparse
import sys
import os
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], '../'))
from instabot import Bot
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('user', type=str, help='user')
args = parser.parse_args()
# Add your bots here
BOTS_DATA = [
{
"username": "user1",
"password": "pass1",
"proxy": "https://127.0.0.1:3128"
},
{
"username": "user2",
"password": "pass2",
"proxy": "https://127.0.0.1:3128"
},
{
"username": "user3",
"password": "pass3",
"proxy": "https://127.0.0.1:3128"
},
{
"username": "user4",
"password": "pass4",
"proxy": "https://127.0.0.1:3128"
},
]
for bot in tqdm(BOTS_DATA):
bot['bot'] = Bot()
bot['bot'].login(username=bot['username'], password=bot['password'], proxy=bot['proxy'])
bot['bot'].follow(args.user)
The only way to follow another user's account would be through using Instagram's API. Unfortunately, Instagram has recently stopped accepting applications for the relationships scope which permits such an action — refer to the Instagram documents here.
I cannot offer any advice on the matter, but you will also want to ensure you're building an application which aligns with Instagram's Terms of Use and Platform Policy.
An alternative option to explore might be to look at automation with twill, for example — How can I login to a website with Python?

Categories

Resources