コード例 #1
0
ファイル: __init__.py プロジェクト: toddbirchard/jamstack-api
async def new_account(new_account_event: NetlifyUserEvent,
                      db: Session = Depends(get_db)):
    """
    Create user account from Netlify identity signup.

    :param NetlifyUserEvent new_account_event: Newly created user account from Netlify.
    :param Session db: ORM Database session.

    :returns: NetlifyAccountCreationResponse
    """
    account = new_account_event.user
    db_account = get_account(db, account.email)
    if db_account:
        LOGGER.warning(f"User account already exists for `{account.email}`.")
        raise HTTPException(
            status_code=400,
            detail=f"User account already exists for `{account.email}`.",
        )
    create_account(db, account)
    db_account_created = get_account(db, account.email)
    if db_account_created:
        LOGGER.success(
            f"Account created: id={account.id} email={account.email}, name={account.user_metadata.full_name}"
        )
        return NetlifyAccountCreationResponse(
            succeeded=new_account_event,
            failed=None,
        )
    LOGGER.warning(
        f"Account not created: id={account.id} email={account.email}, name={account.user_metadata.full_name}"
    )
    return NetlifyAccountCreationResponse(
        succeeded=None,
        failed=new_account_event,
    )
コード例 #2
0
ファイル: __init__.py プロジェクト: toddbirchard/jamstack-api
async def upvote_comment(upvote_request: UpvoteComment,
                         db: Session = Depends(get_db)):
    """
    Cast a user upvote for another user's comment.

    :param UpvoteComment upvote_request: User-generated request to upvote a comment.
    :param Session db: ORM Database session.
    """
    existing_vote = get_comment_upvote(db, upvote_request.user_id,
                                       upvote_request.comment_id)
    if upvote_request.vote and existing_vote is None:
        submit_comment_upvote(db, upvote_request.user_id,
                              upvote_request.comment_id)
        return upvote_request
    elif upvote_request.vote and existing_vote:
        LOGGER.warning(
            f"Upvote already submitted for comment `{upvote_request.comment_id}` from user `{upvote_request.user_id}`."
        )
        raise HTTPException(
            status_code=400,
            detail=
            f"Upvote already submitted for comment `{upvote_request.comment_id}` from user `{upvote_request.user_id}`.",
        )
    elif upvote_request.vote is False and existing_vote:
        remove_comment_upvote(db, upvote_request.user_id,
                              upvote_request.comment_id)
        return upvote_request
    LOGGER.warning(
        f"Can't delete non-existent upvote for comment `{upvote_request.comment_id}` from user `{upvote_request.user_id}`."
    )
    raise HTTPException(
        status_code=400,
        detail=
        f"Can't delete non-existent upvote for comment `{upvote_request.comment_id}` from user `{upvote_request.user_id}`.",
    )
コード例 #3
0
ファイル: __init__.py プロジェクト: toddbirchard/jamstack-api
async def update_post(post_update: PostUpdate) -> JSONResponse:
    """
    Enrich post metadata upon update.

    :param PostUpdate post_update: Request to update Ghost post.

    :returns: JSONResponse
    """
    previous_update = post_update.post.previous
    if previous_update:
        current_time = get_current_datetime()
        previous_update_date = datetime.strptime(
            str(previous_update.updated_at), "%Y-%m-%dT%H:%M:%S.000Z"
        )
        if previous_update_date and current_time - previous_update_date < timedelta(
            seconds=5
        ):
            LOGGER.warning("Post update ignored as post was just updated.")
            raise HTTPException(
                status_code=422, detail="Post update ignored as post was just updated."
            )
    post = post_update.post.current
    slug = post.slug
    feature_image = post.feature_image
    html = post.html
    body = {
        "posts": [
            {
                "meta_title": post.title,
                "og_title": post.title,
                "twitter_title": post.title,
                "meta_description": post.custom_excerpt,
                "twitter_description": post.custom_excerpt,
                "og_description": post.custom_excerpt,
                "updated_at": get_current_time(),
            }
        ]
    }
    if html and "http://" in html:
        body = update_html_ssl_links(html, body, slug)
    if feature_image is not None:
        body = update_metadata_images(feature_image, body, slug)
    sleep(1)
    time = get_current_time()
    body["posts"][0]["updated_at"] = time
    response, code = ghost.update_post(post.id, body, post.slug)
    LOGGER.success(f"Successfully updated post `{slug}`: {body}")
    return JSONResponse({str(code): response})
コード例 #4
0
def get_donation(db: Session, donation: NewDonation) -> Optional[NewDonation]:
    """
    Fetch BuyMeACoffee donation by ID.

    :param Session db: ORM database session.
    :param NewDonation donation: Donation record to be fetched.

    :returns: Optional[NewDonation]
    """
    existing_donation = (db.query(Donation).filter(
        Donation.coffee_id == donation.coffee_id).first())
    if existing_donation is None:
        return donation
    LOGGER.warning(
        f"Donation `{existing_donation.id}` from `{existing_donation.email}` already exists; skipping."
    )
    return None
コード例 #5
0
def manage_sessions():
    '''This method is called before every request. Checks to see if there a session associated with the current request.
    If there is then update the last interaction time on that session.
    '''
    if SESSION_HANDLER.is_expired(
            bottle.request.session.id
    ):  # Someone is trying to use a session that we have deleted due to inactivity
        SESSION_HANDLER.cleanup_expired_session(bottle.request.session.id)
        bottle.request.session.delete(
        )  # TODO: I'm not sure how the actual session is deleted on the client side
        LOGGER.info("Cleaning up an out of date session")
    elif not SESSION_HANDLER.is_active(bottle.request.session.id):
        LOGGER.warning(
            "We are getting a request that doesn't have an active session")
    else:
        SESSION_HANDLER.touch_session(
            bottle.request.session.id
        )  # let the SESSION_HANDLER know that this session has activity
コード例 #6
0
    def __init__(self, session_id, port):
        self.session_id = session_id

        self.max_retries = 30
        self.rety_timeout = 2
        self.connection = None

        i = 0
        while self.connection is None or i < self.max_retries:
            try:
                self.connection = rpyc.connect(
                    "localhost", port, config={'allow_public_attrs': False})
                LOGGER.info("Made a connection")
                break
            except ConnectionRefusedError:
                i += 1
                time.sleep(self.rety_timeout)
                LOGGER.warning("Haven't connected, attempt %d" % (i))
コード例 #7
0
ファイル: mixpanel.py プロジェクト: toddbirchard/jamstack-api
def create_mixpanel_record(user: Member) -> Optional[dict]:
    """
    Add user record to Mixpanel.

    :param Member user: New user account from Netlify auth.

    :returns: Optional[dict]
    """
    try:
        mp = Mixpanel(settings.MIXPANEL_API_TOKEN)
        body = {"$name": user.name, "$email": user.email}
        new_user = mp.people_set(user.email, body)
        if new_user:
            return new_user
        return None
    except MixpanelException as e:
        LOGGER.warning(f"Mixpanel failed to register user: {e}")
    except Exception as e:
        LOGGER.warning(
            f"Unexpected failure when registering Mixpanel user: {e}")
コード例 #8
0
# Read environment variables
host = getenv("REMOTE_HOST")
username = getenv("REMOTE_USERNAME")
password = getenv("REMOTE_PASSWORD")
ssh_key_filepath = getenv("SSH_KEY_FILEPATH")
remote_path = getenv("REMOTE_PATH")
config_values = [
    {
        "host": host
    },
    {
        "user": username
    },
    {
        "password": password
    },
    {
        "ssh": ssh_key_filepath
    },
    {
        "path": remote_path
    },
]

for config in config_values:
    if None in config.values():
        LOGGER.warning(f"Config value not set: {config.popitem()}")
        raise Exception("Set your environment variables via a .env file.")

local_file_directory = "files"