Exemplo n.º 1
0
def use_logging_handler():
    # [START logging_handler_setup]
    # Imports the Google Cloud client library
    import google.cloud.logging

    # Instantiates a client
    client = google.cloud.logging.Client()

    # Connects the logger to the root logging handler; by default this captures
    # all logs at INFO level and higher
    client.setup_logging()
    # [END logging_handler_setup]

    # [START logging_handler_usage]
    # Imports Python standard library logging
    import logging

    # The data to log
    text = 'Hello, world!'

    # Emits the data using the standard logging module
    logging.warning(text)
    # [END logging_handler_usage]

    print('Logged: {}'.format(text))
Exemplo n.º 2
0
def orders_paid():
    """
    This is the public endpoint (no auth) for shopify orders_paid webhook.
    """
    data = flask.request.json
    logging.info(f'Receiving orders_paid request {data}')
    if data.get('topic') != 'ORDERS_PAID':
        logging.warning(f'Invalid not ORDERS_PAID data received {data}')
    elif not data.get('domain') or not data.get('payload'):
        logging.warning(f'Invalid shop/customer data received {data}')
    else:
        try:
            shop = data.get('domain')
            order_id = data.get('payload').get('id')
            customer_id = data.get('payload').get('customer').get('id')
            payload = data.get('payload')
            res = sql_handler.save_orders_paid(shop, order_id, customer_id,
                                               payload)
            if res.status_code == 200:
                logging.info('Data saved to cloud SQL')
        except Exception as e:
            logging.error(f'Saving events error: {e}')
    response = flask.jsonify('OK')
    response.status_code = 200
    return response
Exemplo n.º 3
0
def fetch_single_profile(force_update, userId, social_platform='instagram'):
    profile = None

    if not force_update:
        profile, update_time = sql_handler.get_profile(
            userId, platform=social_platform)
        logging.info(
            f'Not forcing profile update, and obtained profile {profile}')
    if not profile or len(profile) == 0:
        for i in range(0, 5):
            logging.info(
                f'Fetching profile from Modash for userid {userId}: # {i+1}th try'
            )
            url = f'{MODASH_API_ENDPINT}/{social_platform}/profile/{userId}/report'
            logging.info(f'Receiving request for url {url}')
            headers = {'Authorization': MODASH_AUTH_HEADER}
            profile_res = requests.get(url, headers=headers)
            profile_json = profile_res.json()
            logging.info(
                f'Modash {social_platform} profile response is: {profile_res.json()}'
            )
            profile = profile_json.get('profile')
            if profile:
                save_modash_profile_firebase(userId, profile, social_platform)
                sql_handler.save_profile(userId, social_platform, profile)
                break
            else:
                logging.warning('Modash API not responding, retrying')
                time.sleep(1)
    return profile
Exemplo n.º 4
0
def track():
    """
    public endpoint (no auth)
    Note: Shopify client side is using the following code snippet to send tracking events:
    # req.send(JSON.stringify({
    #     lifo_tracker_id: lifo_tracker_id,
    #     shop: getShop(),
    #     location: document.location,
    #     navigator: navigator.userAgent,
    #     referrer: document.referrer,
    #     discount_code,
    # })),
    """
    data = flask.request.json
    logging.info(f'Receiving /track request {data}')
    if not data.get('shop'):
        logging.warning(f'Invalid shop data received {data}')
    elif not data.get('lifo_tracker_id'):
        logging.debug(f'Skip none lifo event {data}')
    else:
        try:
            res = sql_handler.save_track_visit(data)
            if res.status_code == 200:
                logging.info('Data saved to cloud SQL')
        except Exception as e:
            logging.error(f'Saving events error: {e}')
    response = flask.jsonify({'status': 'OK'})
    response.status_code = 200
    return response
Exemplo n.º 5
0
def use_logging_handler():
    # [START logging_handler_setup]
    # Imports the Cloud Logging client library
    import google.cloud.logging

    # Instantiates a client
    client = google.cloud.logging.Client()

    # Retrieves a Cloud Logging handler based on the environment
    # you're running in and integrates the handler with the
    # Python logging module. By default this captures all logs
    # at INFO level and higher
    client.get_default_handler()
    client.setup_logging()
    # [END logging_handler_setup]

    # [START logging_handler_usage]
    # Imports Python standard library logging
    import logging

    # The data to log
    text = 'Hello, world!'

    # Emits the data using the standard logging module
    logging.warning(text)
    # [END logging_handler_usage]

    print('Logged: {}'.format(text))
Exemplo n.º 6
0
def verify_auth_status():
    """
    This is an API that verifies the authorization status. Called when user loads up the page.
    """
    from cloud_sql import sql_handler
    uid = flask.session['uid']
    logging.info(f'verifying auth sync status for uid {uid}')
    access_token, email = sql_handler.get_nylas_authorize_info(uid)
    if not access_token:
        logging.info(f'The account {uid} has not authorized yet')
        response = flask.jsonify({'status': 'no auth'})
        response.status_code = 402
        return response
    try:
        nylas_client = APIClient(
            app_id=app.config["NYLAS_OAUTH_CLIENT_ID"],
            app_secret=app.config["NYLAS_OAUTH_CLIENT_SECRET"],
            access_token=access_token,
        )
        sync_state = nylas_client.account.sync_state
        logging.info(f'Current syncing status is {sync_state}')
        logging.info(f'The account {uid} is in sync')
        response = flask.jsonify({'email': email or flask.session['email']})
        response.status_code = 200
        return response
    except Exception as e:

        # Here we simplify the status into binary cases.
        # for more statuses, check https://docs.nylas.com/reference#account-sync-status
        logging.warning(f'The account {uid} need resync')
        response = flask.jsonify({'status': 'Need resync'})
        response.status_code = 200
        return response
Exemplo n.º 7
0
    def archiveLog(self, job, wsdef, workstepLog ):
        proj = self.projects[job.projectId]

        # un-backslash filename in case of windows shenanigans
        workstepLog = self.unbackslashPath( workstepLog )

        # Check that we're configured to publish stuff
        if not proj.bucketName:
            logging.warning("archiveLog: No bucketName set in project, can't archive log.")
            return False

        # Make sure the file exists
        if not os.path.exists(workstepLog):
            logging.warning( f"archiveLog: Workstep log file {workstepLog} does not exist." )
            return False
        else:
            logging.info(f"Archiving {workstepLog} to bucket {proj.bucketName}")
            if self.storage_client is None:
                self.storage_client = google.cloud.storage.Client()

            logFilename = os.path.split(workstepLog)[-1]
            bucket = self.storage_client.bucket(proj.bucketName)
            blobName = self.unbackslashPath( os.path.join(proj.projectId, job.jobKey, "logs", logFilename) )
            blob = bucket.blob(blobName)
            result = blob.upload_from_filename(workstepLog, content_type="text/plain;charset=UTF-8")

            logArchiveUrl = f"https://{bucket.name}.storage.googleapis.com/{blob.name}"
            logging.info(f"Result of upload is {logArchiveUrl}")
Exemplo n.º 8
0
def rate(request, post_channel, post_user, type, post_url):
    logging.debug('rate: C=%s U=%s T=%s P=%s' %
                  (post_channel, post_user, type, post_url))
    types = ['up', 'down', 'wtf', 'nsfw']
    if type in types:
        name = ''.join(
            re.findall(
                '[a-zA-Z0-9_-]', post_channel + '_' + post_user + '_' + type +
                '_' + post_url))[:500]
        try:
            taskqueue.add(name=name,
                          queue_name='default',
                          url='/tasks/rate',
                          params={
                              'channel': post_channel,
                              'post_user': post_user,
                              'type': type,
                              'post_url': post_url
                          })
        except taskqueue.TombstonedTaskError:
            logging.warning('Duplicate task name %s' % name)

    else:
        logging.warning('Wrong type (%s)! %s %s %s' %
                        (type, post_channel, post_user, post_url))
    return HttpResponseRedirect('/url/')
Exemplo n.º 9
0
    def post(self):
        post_channel = self.request.get('post_channel', '')
        post_user = self.request.get('post_user', '')
        post_url = self.request.get('post_url', '')
        post_extra = self.request.get('extra', '')

        # Related/tag
        if post_extra.startwith('#'):
            # TODO: check
            if post_extra[1:].isdigit():
                type = 'related'
            else:
                type = 'tag'
        else:
            type = 'comment'

        url = Url.all().filter('url =', post_url).get()
        channel = Channel.all().filter('name =', post_channel).get()
        channelurl = ChannelUrl.all().filter('channel =',
                                             channel).filter('url =',
                                                             url).get()
        if channelurl:
            extra = Extra()
            extra.channelurl = channelurl
            extra.user = post_user
            setattr(extra, type, post_extra)
            extra.put()
        else:
            logging.warning('ChannelUrl not found: %s %s' %
                            (post_channel, post_url))
Exemplo n.º 10
0
    def workstepFetch(self, job, wsdef, fpLog ):

        proj = self.projects[job.projectId]

        pristineRepoPath = self.updatePristineRepo( proj, wsdef, fpLog )
        if not pristineRepoPath:
            return False

        # Now clone the pristine repo into the work dir
        workdirRepoPath = os.path.join( proj.workDir, job.jobDirShort )
        if os.path.exists( workdirRepoPath ):
            # Might make this a fatal error later, or nuke and re-copy this dir, but for
            # now we'll allow this to make debugging easier.
            logging.warning( f"Workdir repo {workdirRepoPath} already exists, using that.")
        else:
            gitCloneCommand = [ "git", "clone", pristineRepoPath, workdirRepoPath ]
            retVal, cmdTime = self.echoRunCommand(gitCloneCommand, fpLog)
            if retVal:
                return False

        # Now bring the workdir copy of the repo up to date with what we're
        # trying to build
        gitCheckoutCommand = [ "git", "-C", workdirRepoPath,
                               "checkout", job.commitVer ]
        retVal, cmdTime = self.echoRunCommand( gitCheckoutCommand, fpLog )
        if retVal:
            return False

        return True
Exemplo n.º 11
0
    def publishArtifact( self, proj, job, wsdef, workdirRepoPath ):

        # Check that we're configured to publish stuff
        if not proj.bucketName:
            logging.warning("publishArtifact: No bucketName set in project, can't publish.")
            return False

        # Make sure the file exists
        artifactFile = wsdef.artifact
        artifactFile = self.replacePathVars( artifactFile, workdirRepoPath, proj, job )
 
        if not os.path.exists( artifactFile ):
            failMsg = f"Artifact file {artifactFile} does not exist."
            logging.warning( failMsg )
            job.lastError = failMsg
            return False
        else:
            logging.info( f"Publishing {artifactFile} to bucket {proj.bucketName}")
            if self.storage_client is None:
                self.storage_client = google.cloud.storage.Client()

            artifactFileName = os.path.split( artifactFile )[-1]
            bucket = self.storage_client.bucket( proj.bucketName )
            blobName = self.unbackslashPath( os.path.join( proj.projectId, job.jobKey, artifactFileName) )
            
            blob = bucket.blob( blobName )
            result = blob.upload_from_filename( artifactFile )

            artifactUrl = f"https://storage.googleapis.com/{bucket.name}/{blob.name}"
            logging.info( f"Result of upload is {artifactUrl}")


            # Make an artifact entry in the DB
            artifact = TKArtifact()
            artifact.project = proj.projectId
            artifact.commitVer = job.commitVer
            artifact.jobKey = job.jobKey
            artifact.builtfile = artifactUrl

            # If the artifact has a manifestBundleId, make a manifest for it
            if proj.manifestBundleId:
                artifact.addManifestInfo( proj.manifestAppTitle, proj.manifestBundleId, job.version, job.buildNum, artifactUrl )

                # maybe want to make this more configurable
                manifestName = f"{proj.projectId}_manifest_{job.version}_build_{job.buildNum}.plist"
                manifestBlobName = os.path.join( proj.projectId, job.jobKey, manifestName)
                manifestBlob = bucket.blob( manifestBlobName )
                result = manifestBlob.upload_from_string( artifact.generateManifestFile())

                manifestUrl = f"https://storage.googleapis.com/{bucket.name}/{manifestBlob.name}"
                artifact.manifest['manifestURL'] = manifestUrl
                logging.info( f"Uploaded IOS manifest to {manifestUrl}" )


            pubArtifactRef = self.db.collection(u'artifacts').document()
            pubArtifactRef.set( artifact.toFirebaseDict() )
            logging.info( f"Added artifact with ref {pubArtifactRef.id}")

            return True
Exemplo n.º 12
0
def info(request):
    today = datetime.date.today()
    now = datetime.datetime.now()

    l = list(string.ascii_uppercase)
    l.append('Z')

    DEFAULT_COUNTER_NAME = chr(now.isocalendar()[0] - 2010 +
                               65) + l[(now.isocalendar()[1] - 1) / 2]

    id = None
    url = None
    if request.method == "POST":
        try:
            data = simplejson.loads(request.raw_post_data)

            id = str(data.get('id', '')).upper()
            url = data.get('url', '')
            logging.debug('id: %s/url: %s' % (id, url))
        except Exception as e:
            logging.warning('Error %s' % (e))
    try:
        id = int(id)
        if id < 1000:
            id = DEFAULT_COUNTER_NAME + str(id)
            # logging.debug('%s' % id)
    except:
        pattern1 = r'^[A-Z]{1}$'
        pattern2 = r'^[A-Z]{2}$'
        if re.match(pattern1, id):
            id = DEFAULT_COUNTER_NAME[0] + str(id)
            # logging.debug('%s' % id)
            id = id + str(counter.get_count(id))
            # logging.debug('%s' % id)
        elif re.match(pattern2, id):
            id = id + str(counter.get_count(id))
    channelurl = ChannelUrl.get_by_id(id)
    if channelurl:
        url = channelurl.url.get().url
        url_title = channelurl.url.get().title
        rate = channelurl.rating()
        extra = channelurl.extras(plain='True')
        posts = channelurl.posts()
        channel = channelurl.channel.get().name

        retval = simplejson.dumps({
            'id': channelurl.key.id(),
            'url': url,
            'title': url_title,
            'rate': rate,
            'extra': extra,
            'posts': posts
        })
    else:
        retval = simplejson.dumps({'id': 0})
    return HttpResponse(retval, mimetype="application/json")
Exemplo n.º 13
0
def shop_customer_info():
    """
    This endpoint is called upon AM to access Shopify shop products for access_token
    """
    shop = flask.request.args.get('shop')
    days_range = flask.request.args.get('days_range')
    try:
        days_range = int(days_range)
    except Exception as e:
        logging.warning('Illegal days_range, revert to default value')
        days_range = DEFFAULT_DATE_RANGE
    res = get_shopify_access_token(shop)
    if not res:
        res = {'status': 'access token not found'}
        response = flask.jsonify(res)
        response.status_code = 404
        return response
    shop_access_token = res

    if request.method == 'PUT':
        created_at_min = datetime.datetime.now() - datetime.timedelta(
            days=days_range)
        url = f'https://{shop}/admin/api/{API_VERSION}/customers.json'
        logging.info(f'Receiving request for url {url}')
        headers = {"X-Shopify-Access-Token": shop_access_token}
        params = {
            'limit': MAX_SHOPIFY_RESULTS_LIMIT,
            'created_at_min': created_at_min.isoformat()
        }
        res = requests.get(url, headers=headers, params=params)
        data = res.json()

        logging.info(f'Obtained shop information for shop {shop}: {data}')
        customers = data.get('customers')
        if customers:
            for customer_json in customers:
                customer_id = customer_json.get('id')
                sql_handler.save_customer_info(shop, customer_id,
                                               customer_json)
            logging.info(f'Saved {len(customers)} for shop {shop}')
        else:
            logging.info('No customers found')
    else:
        logging.info(f'Getting customer location data for shop {shop}')
        query_results = sql_handler.get_shop_customers_locations(shop)
        data = []
        for row in query_results:
            cur_res = {}
            cur_res['city'] = row[0]
            cur_res['province'] = row[1]
            cur_res['location_cnt'] = row[2]
            data.append(cur_res)
    response = flask.jsonify(data)
    response.status_code = 200
    return response
Exemplo n.º 14
0
    def createFromConfigFile(cls, agentConfigFile ):

        # Use where the agent Cfg is located as the default for the build dir
        defaultTkBuildDir = os.path.split( agentConfigFile )[0]

        if not os.path.exists(agentConfigFile):
            logging.warning("WARN: agent config file doesn't exist or can't be read:", agentConfigFile)
        else:
            with open(agentConfigFile) as fpconfig:
                configData = yaml.full_load(fpconfig)
                return cls.createFromConfig( configData, defaultTkBuildDir )
Exemplo n.º 15
0
def send_message_to_pubsub(message, file_name, storage_bucket_name):
    publisher = pubsub_v1.PublisherClient()

    logging.warning("PubSub: {} to topic: {}".format(message,
                                                     topic_name_output))
    message = message.encode('utf-8')
    topic_path = publisher.topic_path(project_id, topic_name_output)
    status = publisher.publish(topic_path,
                               message,
                               object=label_to_detect,
                               file_name=file_name,
                               storage_bucket_name=storage_bucket_name)
Exemplo n.º 16
0
    def peekVersion( self, job, versionFile ):

        if not os.path.exists( versionFile ):
            logging.warning( f"Version file {versionFile} does not exist.")
            return

        with open( versionFile ) as fp:
            verLine = fp.readline().strip()

            if verLine:
                job.version = verLine
                logging.info( f"PeekVersion: Version is {job.version}" )
Exemplo n.º 17
0
    def serverUpdate(self):

        logging.info( f"Agent update ... {self.updCount}")
        self.updCount += 1

        print( f" {len(self.jobList)} avail jobs:")

        # Report our status to the server
        self.updateCurrentStatus( AgentStatus.IDLE )

        # Check if there are any obsolete jobs, and delete them
        self.cleanupObsoleteJobs()

        # Check if there are any jobdirs that do not exist in the job list. If so, clean up those job dirs.
        self.cleanupOldJobDirs()

        # Check if there are jobs we can do
        for job in self.jobList:

            proj = self.projects[job.projectId]

            # Ignore jobs with tags we can't match
            if not self.matchTags( job.tags, self.agentInfo.tags ):
                print("Skipping job with tags ", job.tags, "our tags are ", self.agentInfo.tags )
                continue

            # Ignore jobs marked "RUN" ... this might be running on another node (todo) but
            # probably is just stale because firebase updates are not instant.
            if JobStatus.RUN in job.worksteps.values():
                logging.warning("Job is marked RUN?? but we're not running it.")
                #sys.exit(1)
                continue

            # If the job has work left to do
            if job.hasWorkRemaining( proj.workstepNames ):
                print("job ", job, "has work left...")
                self.currentJob = job
                break
            else:
                print( "No work remains", job, job.worksteps )


        # Did we find a job to run?
        if self.currentJob == None:
            logging.info("No matching jobs found to run.")
        else:
            # run the job
            self.runNextJobStep( self.currentJob )

            # clear the current job
            self.currentJob = None
Exemplo n.º 18
0
    def get(self):
        doc_id = self.request.get('doc_id', '')
        if doc_id:
            try:
                prefix = self.request.get('prefix', '')
                name = str(prefix) + str(doc_id)
                taskqueue.add(name=name,
                              queue_name='document',
                              url='/tasks/update_document',
                              params={'doc_id': doc_id})
            except taskqueue.TombstonedTaskError:
                logging.warning('TombstonedTaskError %s' % (name))
            except taskqueue.TaskAlreadyExistsError:
                logging.warning('TaskAlreadyExistsError %s' % (name))

        else:
            doc_ids = []
            url_keys = Url.query().order(Url.document_date).fetch(
                100, keys_only=True)

            for key in url_keys:
                doc_id = key.id()
                try:
                    prefix = self.request.get('prefix', '')
                    name = str(prefix) + str(doc_id)
                    taskqueue.add(name=str(doc_id),
                                  queue_name='document',
                                  url='/tasks/update_document',
                                  params={'doc_id': str(doc_id)})
                except taskqueue.TombstonedTaskError:
                    logging.warning('TombstonedTaskError %s' % (str(name)))
                except taskqueue.TaskAlreadyExistsError:
                    logging.warning('TaskAlreadyExistsError %s' % (str(name)))
Exemplo n.º 19
0
def garagecommand_callback(message):
    logging.info(f"Received command: {message.data}")
    try:
        msgDict = json.loads(message.data)
    except:
        logging.warning("Bad command, ignoring...")
        return
    cmd = msgDict.get('command')
    if cmd:
        if cmd == "open":
            import garagedoorgpio
            garagedoorgpio.open_door()
        elif cmd == "close":
            import garagedoorgpio
            garagedoorgpio.close_door()
        else:
            logging.warning(f"Unknown command: {msgDict['command']}")
        message.ack()
Exemplo n.º 20
0
def request_handling():

    logging.warning('Arguments: {}'.format(request.args))
    logging.warning('Method: {}'.format(request.method))
    logging.warning('URL: {}'.format(request.url))

    if request.method == 'POST':
        result = request.form
        logging.warning(result)

    return "ok"
Exemplo n.º 21
0
def modash_match():
    filters = flask.request.json
    if not filters:
        response = flask.jsonify({"error": "None empty post body required!"})
        response.status_code = 412
        return response
    field_range_filters = filters.get('field_range_filters')
    field_contain_filters = filters.get('field_contain_filters')
    prefix_filters = filters.get('prefix_filters')

    modash_profile_ref = db.collection('modash')
    if field_range_filters:
        logging.warning('Field range filters are not supported in server side')
    modash_profile_ref = prefix_filters_handler(modash_profile_ref,
                                                prefix_filters)
    snap_list = modash_profile_ref.limit(1000).get()
    results = [doc.to_dict().get('profile_json') for doc in snap_list]
    response = flask.jsonify(results)
    response.status_code = 200
    return response
Exemplo n.º 22
0
def extra(request, post_channel, post_user, extra, post_url):
    logging.debug('rate: C=%s U=%s E=%s P=%s' %
                  (post_channel, post_user, extra, post_url))
    name = ''.join(
        re.findall(
            '[a-zA-Z0-9_-]', post_channel + '_' + post_user + '_' + extra +
            '_' + post_url))[:500]
    try:
        taskqueue.add(name=name,
                      queue_name='default',
                      url='/tasks/extra',
                      params={
                          'channel': post_channel,
                          'post_user': post_user,
                          'extra': extra,
                          'post_url': post_url
                      })
    except taskqueue.TombstonedTaskError:
        logging.warning('Duplicate task name %s' % name)
    return HttpResponseRedirect('/url/')
Exemplo n.º 23
0
    def post(self):
        post_channel = self.request.get('post_channel', '')
        post_user = self.request.get('post_user', '')
        post_url = self.request.get('post_url', '')
        type = self.request.get('type', '')

        url = Url.all().filter('url =', post_url).get()
        channel = Channel.all().filter('name =', post_channel).get()
        channelurl = ChannelUrl.all().filter('channel =',
                                             channel).filter('url =',
                                                             url).get()
        if channelurl:
            rate = Rate()
            rate.channelurl = channelurl
            rate.user = post_user
            rate.type = type
            rate.put()
        else:
            logging.warning('ChannelUrl not found: %s %s' %
                            (post_channel, post_url))
Exemplo n.º 24
0
def post(request, post_url, post_channel=None, post_user=None):
    if not post_user:
        post_user = '******'
    if not post_channel:
        post_channel = '!' + post_user
    logging.debug('post: C=%s U=%s P=%s' % (post_channel, post_user, post_url))
    name = ''.join(
        re.findall('[a-zA-Z0-9_-]',
                   post_channel + '_' + post_user + '_' + post_url))[:500]
    try:
        taskqueue.add(name=name,
                      queue_name='default',
                      url='/tasks/post',
                      params={
                          'post_channel': post_channel,
                          'post_user': post_user,
                          'post_url': post_url
                      })
    except taskqueue.TombstonedTaskError:
        logging.warning('Duplicate task name %s' % name)

    return HttpResponseRedirect('/url/')
Exemplo n.º 25
0
def edit_post(id):
    form = PostForm()
    post = get_model().from_datastore(get_model().read(id, 'Post'))
    file = ''
    if not check_post_author(post['author_id'], current_user.id):
        flash('Only the owner of the post can edit it that post', 'warning')
        return redirect(url_for('blog.view_post', id=post['id']))

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        post_time = datetime.now().timestamp()
        #datetime.now().replace(second=0, microsecond=0)
        try:
            file = file_upload(request.files.get('file'))
            logging.info(file)
            if not file:
                file = post['picture_url']
        except Exception as e:
            logging.warning(e)
            print('Could not upload file, something went wrong error is:{0}'.
                  format(e))
        sql_data = {
            'title': data['title'],
            'content': data['post_data'],
            'author': current_user.name,
            'author_id': current_user.id,
            'updated_timestamp': post_time,
            'timestamp': post['timestamp'],
            'picture_url': file
        }

        post = get_model().update(sql_data, id=id)
        return redirect(url_for('blog.view_post', id=post['id']))

    return render_template("form.html",
                           action='blog.edit_post',
                           post=post,
                           id=post['id'],
                           form=form)
Exemplo n.º 26
0
def post(request):
    # today=datetime.date.today()
    topic = None
    nick = None
    channel = None
    date = None

    retval = {}
    if request.method == "POST":
        logging.debug('raw_post_data %s' % (request.raw_post_data))
        try:
            data = simplejson.loads(request.raw_post_data)
            logging.debug('data %s' % (data))
            topic = data.get('topic')
            channel = data.get('channel')
            nick = data.get('nick')
            date = datetime.datetime.strptime(data.get('date'), '%Y%m%d%H%M')
            logging.debug('date: %s, nick: %s, channel, %s, topic: %s' %
                          (date, nick, channel, topic))
        except Exception as e:
            logging.warning('TOPIC/POST: Somewhere near %s' % (e))
            retval = {'id': 0, 'topic': e}
        else:
            try:
                t = Topic(channel=channel, nick=nick, topic=topic, date=date)
                t.put()
            except Exception as e:
                logging.warning('TOPIC/POST/NEW: Somewhere near %s' % (e))
                retval = {'id': 0, 'topic': e}
            else:
                retval = {'id': t.key.id(), 'topic': topic}
                # TODO private channel?
                # News(content='Topic: %s @ %s' % (topic,channel),link='/topic/').put()
                News(content='Topic',
                     link_text='%s @ %s' % (topic, channel),
                     link='/topic/').put()

    logging.debug('Return: %s' % (retval))
    return HttpResponse(simplejson.dumps(retval), mimetype="application/json")
Exemplo n.º 27
0
def order_complete():
    """
    Public endpoint (no auth)
    Don't confuse this one with Shopify webhook.
    Note: Shopify client side is using the following code snippet to send order_complete events:
    # n.send(JSON.stringify({
    #     lifo_tracker_id: lifo_tracker_id,
    #     shop: getShop(),
    #     location: document.location,
    #     navigator: navigator.userAgent,
    #     referrer: document.referrer,
    #     discount_code,
    #     order_id,
    #     customer_id: data.customer_id,
    #     order_data,
    # }));
    """
    data = flask.request.json
    logging.info(f'Receiving order_complete request {data}')
    if not data.get('shop') or not data.get('order_id') or not data.get(
            'customer_id'):
        logging.warning(f'Invalid shop/customer data received {data}')
    elif not data.get('lifo_tracker_id'):
        logging.debug(f'Skip none lifo event {data}')
    else:
        try:
            order_data = data.get('order_data')
            # we use subtotal_price for calculation, before tax and shipping
            subtotal_price = float(order_data.get('subtotal_price'))
            logging.debug(f'Received order with revenue of {subtotal_price}')
            res = sql_handler.save_order_complete(data, subtotal_price)
            if res.status_code == 200:
                logging.info('Data saved to cloud SQL')
        except Exception as e:
            logging.error(f'Saving events error: {e}')
    response = flask.jsonify({'status': 'OK'})
    response.status_code = 200
    return response
Exemplo n.º 28
0
def entitlement():
    """
    This should be replaced with matching algorithm with human supervision in near future
    before GA. Currently this assumes manual input of entitlement data (from BD and sales team)
    before each POC.
    :return: list of matched "shop" along with potential commission information (to be consumed)
    """
    uid = flask.session['uid']
    user = auth.get_user(uid)
    influencer_email = user.email
    if not influencer_email or not checkers.is_email(influencer_email):
        logging.warning(f'Influencer {user} does not have valid email')
        response = flask.jsonify({'Status': 'Need valid email'})
        response.status_code = 422
        return response
    shops = sql_handler.get_campaign_entitlement(influencer_email)
    res = {
        individual_shop['shop']: individual_shop
        for individual_shop in shops
    }
    response = flask.jsonify(res)
    response.status_code = 200
    return response
Exemplo n.º 29
0
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        data = request.form.to_dict(flat=True)
        data['author'] = current_user.name
        image = ''
        post_time = datetime.now().timestamp()
        try:
            image = file_upload(request.files.get('file'))
            logging.info(image)
            if not image:
                image = 'https://storage.cloud.google.com/badgcloudstorage/pusheen-2019-12-10-233107.jpg'
        except Exception as e:
            logging.warning(e)
            print('Could not upload file, something went wrong error is:{0}'.
                  format(e))

        sql_data = {
            'title': data['title'],
            'content': data['post_data'],
            'author': current_user.name,
            'author_id': current_user.id,
            'timestamp': post_time,
            'picture_url': image
        }
        post = get_model().create(sql_data)

        return redirect(url_for('blog.view_post', id=post['id']))
    else:
        try:
            flash(form.errors["post_data"][0], 'warning')
        except KeyError:
            pass
    return render_template("form.html",
                           action='blog.create_post',
                           post={},
                           form=form)
Exemplo n.º 30
0
    def get(self):
        id = self.request.get('id')
        if id:
            url = Url.get_by_id(int(id))
            if url:
                try:
                    prefix = self.request.get('prefix', '')
                    name = str(prefix) + str(id)
                    taskqueue.add(name=name,
                                  queue_name='urlfetch',
                                  url='/tasks/title',
                                  params={'id': id})
                except taskqueue.TombstonedTaskError:
                    logging.warning('TombstonedTaskError %s' % id)
                except taskqueue.TaskAlreadyExistsError:
                    logging.warning('TaskAlreadyExistsError %s' % id)
            else:
                logging.info('No URL')
        else:
            logging.info('No id')

        redirect = self.request.get('redirect')
        if redirect:
            return self.redirect(redirect)