Exemple #1
0
def delete(id):
    db = firestore.Client()
    venusdoc_ref = db.collection(u'venusdoc').document(id)
    venusdoc_ref.delete()
Exemple #2
0
 def __init__(self):
     self.db_client = firestore.Client()
from google.cloud import firestore

datanase = firestore.Client()

doc = datanase.collection("Batting_History").document("111")

print(doc.get().to_dict())
Exemple #4
0
def collector(event, context):
    # This function doesnt need to know what to do at the moment.
    # in future I may try and extend is to do different things, but for now it has 1 simple role

    # kraken = "https://api.kraken.com/0/public/Ticker?pair=xbteur"
    # luno = "https://api.mybitx.com/api/1/ticker?pair=XBTZAR"

    kraken = "https://api.cryptowat.ch/markets/kraken/btceur/summary"
    luno = "https://api.cryptowat.ch/markets/luno/btczar/summary"
    exch = "https://api.exchangeratesapi.io/latest?base=ZAR"

    timestamp = dt.datetime.now(pytz.utc)
    resp_exch = requests.get(exch)
    resp_luno = requests.get(luno)
    resp_kraken = requests.get(kraken)

    ex_rate = json.loads(resp_exch.content)["rates"]
    ex_rate["timestamp"] = timestamp

    json_luno = formatter(resp_luno, timestamp)
    json_kraken = formatter(resp_kraken, timestamp)

    db = firestore.Client()
    db.collection(u'kraken').document(str(int(timestamp.timestamp()))).set(
        json_kraken, merge=True)
    db.collection(u'luno').document(str(int(timestamp.timestamp()))).set(
        json_luno, merge=True)
    db.collection(u'rates').document(str(int(timestamp.timestamp()))).set(
        ex_rate, merge=True)

    # If you start using luno api: to match kraken
    # stemp = json.loads(resp_luno.content)
    # dat = {}
    # dat["ask_price"] = float(stemp["ask"])
    # dat["ask_whole_lot_vol"] = None
    # dat["ask_lot_vol"] = None

    # dat["bid_price"] = float(stemp["bid"])
    # dat["bid_whole_lot_vol"] = None
    # dat["bid_lot_vol"] = None

    # dat["close_price"] = float(stemp["last_trade"])
    # dat["close_lot_vol"] = None

    # dat["vol_today"] = None
    # dat["vol_last24"] = float(stemp["rolling_24_hour_volume"])

    # dat["vol_weighted_ave_price_today"] = None
    # dat["vol_weighted_ave_price_last24"] = None

    # dat["n_trades_today"] = None
    # dat["n_trades_last24"] = None

    # dat["l_today"] = None
    # dat["l_last24"] = None

    # dat["h_today"] = None
    # dat["h_last24"] = None

    # dat["opening_price_today"] = None

    # # kraken
    # stemp = json.loads(resp_kraken.content)["result"]["XXBTZEUR"]
    # dat = {}
    # dat["ask_price"] = float(stemp["a"][0])
    # dat["ask_whole_lot_vol"] = float(stemp["a"][1])
    # dat["ask_lot_vol"] = float(stemp["a"][2])

    # dat["bid_price"] = float(stemp["b"][0])
    # dat["bid_whole_lot_vol"] = float(stemp["b"][1])
    # dat["bid_lot_vol"] = float(stemp["b"][2])

    # dat["close_price"] = float(stemp["c"][0])
    # dat["close_lot_vol"] = float(stemp["c"][1])

    # dat["vol_today"] = float(stemp["v"][0])
    # dat["vol_last24"] = float(stemp["v"][0])

    # dat["vol_weighted_ave_price_today"] = float(stemp["p"][0])
    # dat["vol_weighted_ave_price_last24"] = float(stemp["p"][0])

    # dat["n_trades_today"] = float(stemp["t"][0])
    # dat["n_trades_last24"] = float(stemp["t"][0])

    # dat["l_today"] = float(stemp["l"][0])
    # dat["l_last24"] = float(stemp["l"][0])

    # dat["h_today"] = float(stemp["h"][0])
    # dat["h_last24"] = float(stemp["h"][0])

    # dat["opening_price_today"] = float(stemp["o"][0])

    # push to BQ
    # if pdf is not None:
    #     client = bigquery.Client()
    #     dataset_ref = client.dataset("exchange_data")
    #     table_ref = dataset_ref.table("exchange_data")

    #     job = client.load_table_from_dataframe(pdf, table_ref, location="US")

    #     job.result()  # Waits for table load to complete.

    #     assert job.state == "DONE"

    return ("success")
Exemple #5
0
    def __init__(self, config_file_path=None):
        self.parse_config_file(config_file_path)
        self.populate_config_parameters()

        self.first_request = True

        # Init client credentials
        self.client_credentials = CloudPasswordLogin(self.login_email, self.login_password, self.api_key)

        self.init_opencv()

        self.ret = None
        self.frame = None
        self.frame_gray = None
        self.prev_frame = np.zeros((self.camera_height, self.camera_width), np.uint8)
        self.prev_frame_gray = np.zeros((self.camera_height, self.camera_width), np.uint8)
        self.movement_detected = False

        for i in range(self.times_to_rotate_by_90_degrees):
            self.prev_frame = np.rot90(self.prev_frame)
            self.prev_frame_gray = np.rot90(self.prev_frame_gray)

        self.latest_image = np.zeros((self.camera_height, self.camera_width), np.uint8)

        # Init URLs
        self.url_base = 'https://firebasestorage.googleapis.com/v0/b/'

        # inference_image_api_url: REST API endpoint for inference image
        # inference_image_url: Binary image content for inference image
        self.inference_image_api_url = (self.url_base
                                       + self.database_id
                                       + ".appspot.com/o/"
                                       + str(self.client_credentials.uid)
                                       + "%2Finference_"
                                       + self.device_id
                                       + ".jpg")

        self.inference_image_url = self.inference_image_api_url + "?alt=media"

        # recorded_image_api_url: REST API for recorded latest image
        # recorded_image_url: Binary image content for recorded latest image
        self.recorded_image_api_url = (self.url_base
                                      + self.database_id
                                      + ".appspot.com/o/"
                                      + str(self.client_credentials.uid)
                                      + "%2Frecorded_"
                                      + self.device_id
                                      + ".jpg")

        self.recorded_image_url = self.recorded_image_api_url + "?alt=media"

        # Init database and storage clients
        # For Cloud Firestore
        self.db = firestore.Client(project=self.database_id, credentials=self.client_credentials)
        self.device_doc = self.db.collection('DEVICES').document(self.device_id)

        # For Cloud Storage
        self.authed_session = AuthorizedSession(self.client_credentials)

        # Get Request Queue IDs
        self.request_queues = None
        self.request_queues_list = []

        self.fetch_request_queues()

        # Initialise the device on Firestore
        try: # Tries to update the device
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect(("8.8.8.8", 80))
                ip = s.getsockname()[0]
            except:
                ip = None

            self.device_doc.update({'device_name': self.device_name,
                                    'recorded_image_url': self.recorded_image_url,
                                    'inference_image_url': self.inference_image_url,
                                    'client_name': self.client_name,
                                    'device_ip': ip})

            s.close()

        except: # If the device document does not exist then create the device document
            try:
                self.device_doc.set({'device_name': self.device_name,
                                     'last_count_date': None,
                                     'last_count_utc_time': None,
                                     'last_count_unix_time': None,
                                     'people_count': None,
                                     'recorded_image_url': self.recorded_image_url,
                                     'inference_image_url': self.inference_image_url,
                                     'client_name': self.client_name})
            except:
                print("UNABLE TO INITIALISE DEVICE ON DATABASE")
 def __init__(self, credentials, project):
     self._client = firestore.Client(credentials=credentials, project=project)
Exemple #7
0
 def get_all(cls):
     db = firestore.Client()
     return [
         cls().populate(**item.to_dict())
         for item in db.collection(cls.collection_name).stream()
     ]
Exemple #8
0
def check_snapshot(request):
    from googleapiclient import discovery
    from google.oauth2 import service_account
    from google.cloud import firestore
    from datetime import datetime
    import pytz

    if request.method == 'POST':
        if request.is_json:
            body = request.get_json(silent=True)
        else:
            return 'json not found', 400

        if 'user' not in body or 'project_id' not in body:
            return 'Wrong parameters', 409
        if 'snapshot_id' not in body or 'debuggee_id' not in body or 'breakpoint_id' not in body:
            return 'Wrong parameters', 409

        project_id = body['project_id']
        user = body['user']
        snap_id = body['snapshot_id']
        debuggee_id = body['debuggee_id']
        breakpoint_id = body['breakpoint_id']
        db = firestore.Client()
        p_ref = db.collection(u'users').document(user).collection(
            u'projects').document(project_id)
        if p_ref.get().exists:
            service_account_info = p_ref.get().to_dict()
        else:
            return 'Service account info not found', 411

        credentials = service_account.Credentials.from_service_account_info(
            service_account_info,
            scopes=['https://www.googleapis.com/auth/cloud-platform'])

        service = discovery.build('clouddebugger',
                                  'v2',
                                  credentials=credentials)
        request = service.debugger().debuggees().breakpoints().get(
            debuggeeId=debuggee_id, breakpointId=snap_id)
        response = request.execute()['breakpoint']
        try:
            if response['isFinalState']:
                # store snapshot info
                snap_ref = p_ref.collection('captured_snapshots').document(
                    snap_id)
                raw_ip = response['stackFrames'][3]['arguments'][1]['members'][
                    15]['value']
                ip_address = raw_ip.split(', ')[0][1:]
                if not snap_ref.get().exists:
                    snap_ref.set({
                        'create_final':
                        response['createTime'] + '/' + response['finalTime'],
                        'breakpoint':
                        breakpoint_id,
                        'ip_address':
                        ip_address
                    })
                    # delete snapshot from running_snapshots
                    p_ref.collection(u'running_snapshots').document(
                        snap_id).delete()
                # create a new snapshot
                b_info = db.collection(u'users').document(user).collection(u'projects').\
                    document(project_id).collection(u'breakpoints').document(breakpoint_id).get().to_dict()
                body = {
                    "action": "CAPTURE",
                    "location": {
                        "path": b_info['file'],
                        "line": b_info['line']
                    }
                }
                request = service.debugger().debuggees().breakpoints().set(
                    debuggeeId=debuggee_id, body=body)
                snap_id = request.execute()['breakpoint']['id']
                print(snap_id, " created")
                tz = pytz.timezone("Zulu")
                snap_ref = p_ref.collection('running_snapshots').document(
                    snap_id)
                snap_ref.set({
                    u'id': snap_id,
                    u'breakpoint_id': breakpoint_id,
                    u'create_time': str(datetime.now(tz))
                })
                return 'All good bro', 201
        except Exception as e:
            print(e)
            return 'Probably Snapshot not captured yet', 202
    return 'Nothing done', 200
Exemple #9
0
def delete_data():
    db = firestore.Client()
    all_titles = db.collection(TITLES_COLLECTION).list_documents()
    for title in all_titles:
        title.delete()
        break
 def get_new_urls(self, domain_name):
     db = firestore.Client()
     new_urls_doc = db.collection(u'domains').document(domain_name)
     new_urls_doc_results = new_urls_doc.get()
     return new_urls_doc_results.to_dict()
Exemple #11
0
def delegate_ML(user):
    csv_str = storege_client.get_bucket("manerun-motions").blob(
        user.csv_id).download_as_string()
    score = Score_generate(csv_str)
    firestore.Client().collection("users").document(user.id).update(
        {"score": score})
 def get_active_feed_urls(self, domain_name, is_active=False):
     db = firestore.Client()
     topic_doc_ref = db.collection(u'feeds').document(domain_name)
     topics = topic_doc_ref.get().to_dict()
     return [topic for topic in topics['topics'] if topic['is_active'] == is_active]
def build_firestore_client() -> firestore.Client:
    return firestore.Client()
Exemple #14
0
def client():
    credentials = service_account.Credentials.from_service_account_file(FIRESTORE_CREDS)
    project = FIRESTORE_PROJECT or credentials.project_id
    yield firestore.Client(project=project, credentials=credentials)
Exemple #15
0
 def get_firestore_client(credentials):
     credentials_info = ServiceAccount.auth(credentials)
     return (firestore.Client(credentials=credentials_info,
                              project=credentials_info.project_id)
             if credentials_info else firestore.Client())
Exemple #16
0
 def __init__(self):
     json_config = json.loads(app.config['FIRESTORE_JSON'])
     credentials = service_account.Credentials.from_service_account_info(json_config)
     self.db = firestore.Client(project="uva-covid19-testing-kiosk",
                                credentials= credentials)
Exemple #17
0
from google.cloud import firestore

urls_collection = firestore.Client().collection(u"urls")


def get_yes_or_no(text):
    answer = input(text)
    if not answer:
        return False

    answer = answer.lower()
    if answer == "y":
        return True
    elif answer == "n":
        return False
    else:
        print("yes or no only")
        return get_yes_or_no(text)


def ask_to_approve(title, url, top_image, text):
    print("title: {}".format(title))
    print("URL: {}".format(url))
    print("top_image url: {}".format(top_image))
    print("################# SUMMARY ###############")
    print(text)
    print("################### END #################")

    return get_yes_or_no("Approve? (y/N)")

Exemple #18
0
def ratings(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    request_json = request.get_json()
    headers = {
        'Access-Control-Allow-Origin': '*',
    }

    try:
        address = request_json.get("address", "")
        product = request_json.get("product", "")
        rating = request_json.get("rating", "")

        if address == "" or product == "" or rating == "":
            return ('invalid-request', 400, headers)

        db = firestore.Client()

        collection_name = "shops"

        doc = db.collection(collection_name).document(address).get()

        if not doc.exists:
            return ("shop-doesn't-exist", 400, headers)

        dic = doc.to_dict()

        print(dic["products"])
        print(len(dic["products"]))

        for prod in dic["products"]:
            print(prod["name"])
            print(product)
            if prod["name"] == product:
                current_rating = prod["rating"]
                print(type(current_rating))
                if rating == "up":
                    current_rating += 1
                elif rating == "down":
                    current_rating -= 1
                else:
                    return ("invalid rating passed", 400, headers)
                prod["rating"] = current_rating
                db.collection(collection_name).document(address).set(dic)
                return ("success", 200, headers)
        return ("item-doesn't-exist", 400, headers)

    except Exception as e:
        return (str(e), 500)
def db():
    yield firestore.Client()
import pytz

from google.cloud import firestore
import google.cloud.exceptions
from flask import Flask, jsonify, abort, Response
import flask

app = Flask(__name__)

app.config["JSONIFY_PRETTYPRINT_REGULAR"] = True

ZEIT_JSON_URL = os.environ["ZEIT_JSON_URL"]
BE_MOPO_CSV_URL = os.environ["BE_MOPO_CSV_URL"]
RL_TS_CSV_URL = os.environ["RL_TS_CSV_URL"]

FIRESTORE = firestore.Client().collection("cache")
FS_NOW_DOC = FIRESTORE.document("gernow-2")
FS_TIMESERIES_DOC = FIRESTORE.document("gerhistory-2")


log = logging.getLogger()
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s.%(msecs)03d %(levelname)s: %(message)s",
    datefmt="%y%m%d-%H:%M:%S",
)


@app.route("/_tasks/update_now")
def task_update_now():
    if flask.request.headers.get("X-Appengine-Cron") or app.debug:
Exemple #21
0
import utils
import publish_utils

from google.cloud import firestore
from google.cloud import pubsub_v1

from datetime import datetime

publisher = pubsub_v1.PublisherClient()
twitter_topic_path = publisher.topic_path(constants.PROJECT_ID, constants.TWITTER_PUBLISH_QUEUE_TOPIC_NAME)
mailsender_topic_path = publisher.topic_path(constants.MAILSENDER_PROJECT_ID,
                                             constants.PUBLISH_NEWSLETTER_QUEUE_TOPIC_NAME)

old_prod_chat_id = "@techtldr"
prod_chat_id = "@overnews"
urls_collection = firestore.Client().collection(u"urls")
newsletter_collection = firestore.Client(
    project=constants.MAILSENDER_PROJECT_ID).collection(u"newsletters")


def publish_to_twitter_topic(title, telegram_url):
    msg_dict = {
        "title": title,
        "url": telegram_url,
        "test": False
    }
    msg_str = json.dumps(msg_dict)
    msg_data = msg_str.encode("utf-8")
    publisher.publish(
        twitter_topic_path, msg_data
    )
 def __init__(self, bot: Bot):
     super(Utility, self).__init__()
     self.bot = bot
     self.fire = firestore.Client()
Exemple #23
0
def fmpfeedback_comment(request: Request) -> Any:
    """Cloud Function HTTP Entrypoint

    Args:
        request (Request): Framework request data

    Returns:
        "OK" if feedback was accepted or an error message with HTTP 4xx status code.
        (Technically, client ignores response content.)
        Anything other than status 2xx will cause client to notify user of failure.
    """
    def _abort_return(client_error: str, internal_error: str = None) -> tuple:
        if internal_error:
            print(f"ERROR! Feedback submit failed: {internal_error}")
        else:
            print(f"ERROR! Feedback submit failed: {client_error}")
        return client_error, 400

    if request.method == "GET":
        # Feedback must be submitted via POST but as a convenience we can at least
        # sanity check the authtoken to help get started.
        if not FEEDBACK_SENDER_AUTHTOKEN:
            err, _ = _abort_return(
                "You must define FEEDBACK_SENDER_AUTHTOKEN as a Runtime Environment Variable. See README for details."
            )
            return err

        abort(405)  # method not allowed

    auth_username = request.authorization.username  # [email protected]/token
    auth_token = request.authorization.password  # FEEDBACK_SENDER_AUTHTOKEN
    x_forwarded_for = next(
        iter(request.headers.get("X-Forwarded-For", "").split(
            ',', 1))).strip()  # IP1 in "IP1, IP2,..., IPN"

    if request.content_type != "application/json":
        return _abort_return("BAD CONTENT")

    if not auth_token:
        return _abort_return("BAD TOKEN")
    if auth_token != FEEDBACK_SENDER_AUTHTOKEN:
        return _abort_return("BAD TOKEN")

    try:
        feedback_json = request.json["request"]
        feedback_email = feedback_json["requester"]["email"]
        feedback_subject = feedback_json["subject"]
        feedback_body = feedback_json["comment"]["body"]
    except KeyError:
        return _abort_return("BAD DATA")

    if not feedback_email:
        return _abort_return("BAD DATA")
    if not feedback_subject:
        return _abort_return("BAD DATA")
    if not feedback_body:
        return _abort_return("BAD DATA")

    if not auth_username:
        return _abort_return("BAD AUTH")
    if auth_username != f"{feedback_email}/token":
        return _abort_return("BAD AUTH")

    feedback_doc = {
        FEEDBACKDOC_FIELD_SUBJECT: feedback_subject,
        FEEDBACKDOC_FIELD_MESSAGE: feedback_body,
    }

    feedback_name = feedback_json["requester"].get("name")  # optional
    if feedback_name:
        feedback_doc[FEEDBACKDOC_FIELD_NAME] = feedback_name

    # An "uploads token" will be included if any files were attached to the feedback submission,
    # in which case it will reference a stub document we need to update with feedback details.
    fs_feedback_doc_id = feedback_json["comment"].get("uploads")
    if fs_feedback_doc_id:
        fs_feedback_doc_id = next(iter(fs_feedback_doc_id))

    if fs_feedback_doc_id:
        print(
            f"Received feedback from: {feedback_email}; uploads stored with feedback {fs_feedback_doc_id}"
        )
    else:
        print(f"Received feedback from: {feedback_email}; no uploads")

    # 1. Store feedback document in Firestore collection

    try:
        fs_client = firestore.Client()

        fs_feedback_coll = fs_client.collection(FEEDBACK_FIRESTORE_COLLECTION)

        if fs_feedback_doc_id:
            # Update details for existing feedback document with attachments
            fs_feedback_doc = fs_feedback_coll.document(fs_feedback_doc_id)
            fs_feedback_doc.update(feedback_doc)
        else:
            fs_feedback_docs = fs_feedback_coll.where(
                FEEDBACKDOC_FIELD_EMAIL, "==",
                feedback_email).where(FEEDBACKDOC_FIELD_ARCHIVEDTIMESTAMP,
                                      "==", "").get()

            # Prevent submitting too much feedback
            if len(fs_feedback_docs) >= FEEDBACK_MAX_PENDING_SUBMITS:
                return _abort_return(
                    "TOO MUCH FEEDBACK",
                    f"TOO MUCH FEEDBACK FROM {feedback_email}")

            feedback_doc.update({
                FEEDBACKDOC_FIELD_EMAIL:
                feedback_email,
                FEEDBACKDOC_FIELD_CREATETIMESTAMP:
                datetime.now(timezone.utc).isoformat(timespec="seconds"),
                FEEDBACKDOC_FIELD_CLIENTIP:
                x_forwarded_for or request.remote_addr,
            })

            # Store feedback document
            _, fs_feedback_doc = fs_feedback_coll.add(FEEDBACK_EMPTY_DOC
                                                      | feedback_doc)
            fs_feedback_doc_id = fs_feedback_doc.id

    except google.auth.exceptions.GoogleAuthError as e:  # GoogleAuthError(Exception)
        return _abort_return(
            "FIRESTORE FAIL",
            f"Feedback Firestore operation failed: Firestore auth exception: {e}"
        )
    except google.api_core.exceptions.ClientError as e:  # ClientError(GoogleAPICallError)
        return _abort_return(
            "FIRESTORE FAIL",
            f"Feedback Firestore operation failed: Firestore client exception: {e}"
        )
    except google.api_core.exceptions.GoogleAPIError as e:  # GoogleAPIError(Exception)
        return _abort_return(
            "FIRESTORE FAIL",
            f"Feedback Firestore operation failed: Firestore API exception: {e}"
        )
    except Exception as e:
        return _abort_return(
            "FIRESTORE FAIL",
            f"Feedback Firestore operation failed: Unexpected exception: {e}")

    # 2. Publish Pub/Sub message to notify subscribers a feedback document was submitted

    try:
        ps_client = pubsub.PublisherClient()

        topic_path = ps_client.topic_path(fs_client.project,
                                          FEEDBACK_PUBSUB_TOPIC)

        try:
            # Topic should have been created before Cloud Functions execute
            topic = ps_client.get_topic(topic=topic_path)
        except google.api_core.exceptions.NotFound:
            return _abort_return(
                "PUBSUB FAIL",
                f"Feedback Pub/Sub {FEEDBACK_PUBSUB_FIELD_ACTION} failed: Topic does not exist: {topic_path}"
            )

        ps_message = json.dumps(
            {
                FEEDBACK_PUBSUB_FIELD_ACTION:
                FEEDBACK_PUBSUB_ACTION_NEWFEEDBACK,
                FEEDBACK_PUBSUB_FIELD_DOCID: fs_feedback_doc_id,
            },
            separators=(',', ':'))

        # Block until publish is complete, raise exception on error
        ps_future = ps_client.publish(topic.name, ps_message.encode())
        ps_event_id = ps_future.result()

    except google.auth.exceptions.GoogleAuthError as e:  # GoogleAuthError(Exception)
        return _abort_return(
            "PUBSUB FAIL",
            f"Feedback Pub/Sub {FEEDBACK_PUBSUB_FIELD_ACTION} publish failed: Pub/Sub auth exception: {e}"
        )
    except google.api_core.exceptions.ClientError as e:  # ClientError(GoogleAPICallError)
        return _abort_return(
            "PUBSUB FAIL",
            f"Feedback Pub/Sub {FEEDBACK_PUBSUB_FIELD_ACTION} publish failed: Pub/Sub client exception: {e}"
        )
    except google.api_core.exceptions.GoogleAPIError as e:  # GoogleAPIError(Exception)
        return _abort_return(
            "PUBSUB FAIL",
            f"Feedback Pub/Sub {FEEDBACK_PUBSUB_FIELD_ACTION} publish failed: Pub/Sub API exception: {e}"
        )
    except Exception as e:
        return _abort_return(
            "PUBSUB FAIL",
            f"Feedback Pub/Sub {FEEDBACK_PUBSUB_FIELD_ACTION} publish failed: Unexpected exception: {e}"
        )
    else:
        print(
            f"Published {FEEDBACK_PUBSUB_FIELD_ACTION} '{FEEDBACK_PUBSUB_ACTION_NEWFEEDBACK}' to Pub/Sub topic: {ps_event_id}"
        )

    return "OK"
Exemple #24
0
import google.auth.credentials

try:
    import googleclouddebugger
    googleclouddebugger.enable(breakpoint_enable_canary=True)
except ImportError:
    pass

app = Flask(__name__)
#create a key
app.secret_key = ''.join(
    secrets.choice(string.ascii_uppercase + string.digits) for i in range(8))

if os.getenv('GAE_ENV', '').startswith('standard'):
    # production
    db = firestore.Client()
else:
    # localhost
    os.environ["FIRESTORE_DATASET"] = "test"
    os.environ["FIRESTORE_EMULATOR_HOST"] = "localhost:8001"
    os.environ["FIRESTORE_EMULATOR_HOST_PATH"] = "localhost:8001/firestore"
    os.environ["FIRESTORE_HOST"] = "http://localhost:8001"
    os.environ["FIRESTORE_PROJECT_ID"] = "test"

    credentials = mock.Mock(spec=google.auth.credentials.Credentials)
    db = firestore.Client(project="test2", credentials=credentials)


def clear_db(db, search_str):
    #Get a new write batch
    batch = db.batch()
Exemple #25
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START run_pubsub_server_setup]
import base64
import os
import sys
import json
import subprocess
from flask import Flask, request
from google.cloud import storage, firestore
app = Flask(__name__)
# [END run_pubsub_server_setup]
firestore_client = firestore.Client()

def download_blob(bucket_name, source_blob_name, destination_file_name):
  """Downloads a blob from the bucket."""
  # bucket_name = "your-bucket-name"
  # source_blob_name = "storage-object-name"
  # destination_file_name = "local/path/to/file"

  storage_client = storage.Client()

  bucket = storage_client.bucket(bucket_name)
  blob = bucket.blob(source_blob_name)
  blob.download_to_filename(destination_file_name)

  print(
    json.dumps(dict(
def setup_db(app):
    db = firestore.Client()
    app.config['DB'] = db
def get_client():
    setup_credentials()
    return firestore.Client()
# because Heroku uses an ephemeral file system (https://devcenter.heroku.com/articles/active-storage-on-heroku)
# we need to write the key that is stored in FIREBASE_SERVICE_ACCOUNT_JSON to a file
# before we can pass it to firebase admin

# the below will error if you haven't set FIREBASE_SERVICE_ACCOUNT_JSON
raw_account = os.environ["FIREBASE_SERVICE_ACCOUNT_JSON"]

ACCOUNT_JSON_FILENAME = "firebase_account_cred.json"

with open(ACCOUNT_JSON_FILENAME, 'w') as account_file:
    account_file.write(raw_account)

# Initialising this on Travis breaks the test suite
if os.environ.get("CI", None) != "true":
    db = firestore.Client("assistive-chess-robot")
    # can't do this in a CI environment
    cred = credentials.Certificate(ACCOUNT_JSON_FILENAME)
    default_app = firebase_admin.initialize_app(cred)
else:
    # reassigned by a mock object
    db = None

GAMES_COLLECTION = "games"
CONTROLLER_COLLECTION = "controllers"
COUNTS_COLLECTION = "counts"

BAD_REQUEST = 400
REQUEST_OK = 'OK'

app = Flask(__name__)
import time

############Explicit Credential environment
path = "/home/pi/Desktop/Parking.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = path

#GPIO starts
s1 = 2
s2 = 21
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(s1, GPIO.IN)
GPIO.setup(s2, GPIO.IN)

#firestore initialization
db = firestore.Client()
doc_ref_s1 = db.collection(u'sensors').document(u'sensor1')
doc_ref_s2 = db.collection(u'sensors').document(u'sensor2')
#here starts main
data1 = 0
data2 = 0
counter = 0
while 1:

    if (GPIO.input(s1) == False):  #car found in slot 1
        data1 = 1
        counter += 1
    else:
        data1 = 0

    print("Received from 1: %s" % data1)
Exemple #30
0
def update(data, venusdoc_id=None):
    db = firestore.Client()
    venusdoc_ref = db.collection(u'venusdoc').document(venusdoc_id)
    venusdoc_ref.set(data)
    return document_to_dict(venusdoc_ref.get())