コード例 #1
0
ファイル: test_utils.py プロジェクト: wleddy/shotglass2
def test_printException():
    with app.app_context():
        # printException((mes="An Unknown Error Occured",level="error",err=None))
        assert utils.printException(mes="Not an error") == "Not an error"
        # create an acutal error
        with pytest.raises(Exception):
            try:
                if nothing == True:
                    pass
            except Exception as e:
                mes =  utils.printException(mes="Should Be error",err=e)
                assert "NameError" in mes
コード例 #2
0
    def _purge(self, keep_days=7):
        """Remove old backup files older than 'keep_days' days old"""

        file_list = self._get_backup_list()
        if file_list:
            for backup_file in file_list:
                try:
                    if os.stat(backup_file).st_mtime < (time.time() -
                                                        (keep_days * 86400)):
                        os.remove(backup_file)
                except Exception as e:
                    printException(
                        "Error in backup file purge for {}".fomat(backup_file),
                        level="error",
                        err=e)
コード例 #3
0
ファイル: transaction.py プロジェクト: wleddy/inventory
def save_record(rec, err_list=[]):
    """Attempt to validate and save a record"""
    if validate_form(rec):
        # Set the sign of qty based on transaction type
        if not rec.qty:
            rec.qty = 0
        else:
            rec.qty = abs(rec.qty)

        if rec.trx_type.lower() == "remove" and rec.qty != 0:
            rec.qty = rec.qty * -1

        Transaction(g.db).save(rec)
        try:
            g.db.commit()
            #Save the date and comment to session
            session['last_trx'] = {"created": rec.created, "note": rec.note}
            return True

        except Exception as e:
            err_list.append(
                printException('Error attempting to save Transaction record',
                               str(e)))

    g.db.rollback()
    return False
コード例 #4
0
ファイル: user.py プロジェクト: wleddy/shotglass2
def set_list_roles():
    """Record the selected roles for the user list page"""
    # import pdb;pdb.set_trace()
    element_name = USER_ROLES_SELECT_OBJ
    if element_name not in request.form:
        element_name = element_name + "[]"  # brackets may be added by jquery or because it's an ajax post?

    selected_values = request.form.getlist(element_name)

    session[USER_ROLES_SELECT_OBJ] = []

    # Use the long form loop in case any of the values submitted do not evalutate with int()
    if selected_values and isinstance(selected_values, list):
        for x in selected_values:
            try:
                session[USER_ROLES_SELECT_OBJ].append(int(x))
            except:
                printException(
                    "Error in user.py.set_list_roles. bad value for USER_ROLES_SELECT_OBJ. -> '{}'"
                    .format(x))

    return "OK"
コード例 #5
0
ファイル: inventory.py プロジェクト: wleddy/inventory
def register_admin():
    
    try:
        g.admin.register(Item,None,display_name='Inv Admin',header_row=True,minimum_rank_required=500)
        g.admin.register(Item,url_for('item.display'),minimum_rank_required=1)
        g.admin.register(Category,url_for('category.display'),display_name='Categories',minimum_rank_required=500)
        g.admin.register(Uom,url_for('uom.display'),display_name='UOM',minimum_rank_required=500)
        g.admin.register(Warehouse,url_for('warehouse.display'),display_name='Warehouses',minimum_rank_required=500)
        g.admin.register(Transaction,url_for('transaction.display'),display_name='Transactions',minimum_rank_required=500,add_to_menu=False)
        g.admin.register(Transfer,url_for('transfer.display'),display_name='Transfers',minimum_rank_required=500,add_to_menu=False)
    except AttributeError as e:
        flash(printException('Unable to register Inventory Access',err=e))
        abort(500)
コード例 #6
0
ファイル: views.py プロジェクト: wleddy/shotglass2
    def save(self):
        try:
            self.table.save(self.rec)
            self.rec_id = self.rec.id

        except Exception as e:
            self.db.rollback()
            self.result_text = printException(
                'Error attempting to save {} record.'.format(
                    self.table.display_name), "error", e)
            flash(self.result_text)
            self.success = False
            return

        self.before_commit_hook()  # anyting special you want to do
        if not self.success:
            self.db.rollback()
            if not self.result_text:
                self.result_text = "Unknown error in before_commit_hook"
            printException(self.result_text, 'error')
            raise RuntimeError

        self.table.commit()
コード例 #7
0
def email_admin(subject=None, message=None):
    """
        Shortcut method to send a quick email to the admin
    """
    try:
        site_config = get_site_config()
        if not subject:
            subject = "An alert was sent from {}".format(
                site_config['SITE_NAME'])

        if not message:
            message = "An alert was sent from {} with no message...".format(
                site_config['SITE_NAME'])

        return send_message(
            None,
            subject=subject,
            body=message,
        )
    except Exception as e:
        mes = "Not able to send message to admin."
        printException(mes, err=e)
        return (False, mes)
コード例 #8
0
    def _text_to_numeric(self,field_name,value,column_type):
        """Attempt to coerce values for numeric fields to numbers if needed.
        
        Params:
        
            field_name: the name of the field being updated
            
            value: the value to convert
            
            column_type: the text name of the field type e.g. INTEGER, REAL, etc.
            
        Return the number or the original value if not successful
        
        Alerts admin on failure
        
        """
        
        from shotglass2.shotglass import get_site_config

        value = value.strip()
        column_type = column_type.upper()
        
        if type(value) != str:
            #safety valve
            return value
            
        if value == '':
           value = None
        elif value.isdigit():
           # convert to int
           value = int(value)
        else:
           # may be a float
           try:
               value = float(value)
               if column_type in self.integer_types:
                   value = int(value)
           except Exception as e:
                mes ="""A problem occurred while attempting to save the record for table {}. 
                It looks like a non-numeric value ('{}') was entered in the field '{}'.
                
                The information in the record may not be what you expect...

                """.format(self.table_name.title(),value,field_name)
                if not get_site_config()['TESTING']:
                    flash(mes)
                self.alert_admin(printException(mes,err=e))
               
        return value
コード例 #9
0
def edit(id=None):
    setExits()
    g.title = "Edit {} Record".format(g.title)

    warehouse = Warehouse(g.db)

    if request.form:
        id = request.form.get('id', None)
    id = cleanRecordID(id)

    if id >= 0 and not request.form:
        if id == 0:
            rec = warehouse.new()
        else:
            rec = warehouse.get(id)

        if rec:
            return render_template('warehouse_edit.html', rec=rec)
        else:
            flash('Record not Found')

    if request.form:
        if not validate_form():
            return render_template('warehouse_edit.html', rec=request.form)

        if id == 0:
            rec = warehouse.new()
        else:
            rec = warehouse.get(id)
        if rec:
            warehouse.update(rec, request.form)
            warehouse.save(rec)
            try:
                g.db.commit()
            except Exception as e:
                g.db.rollback()
                flash(
                    printException('Error attempting to save Warehouse record',
                                   str(e)))
                return redirect(g.listURL)
        else:
            flash('Record not Found')

    return redirect(g.listURL)
コード例 #10
0
def save_record(rec):
    """Attempt to validate and save a record"""

    #import pdb;pdb.set_trace()

    transfer = Transfer(g.db)
    trx_table = Transaction(g.db)

    transfer.update(rec, request.form)
    if validate_form(rec):
        if rec.id:
            ## delete the current transfer record.
            trx_table.delete(cleanRecordID(rec.out_trx_id))
            trx_table.delete(cleanRecordID(rec.in_trx_id))
            ## related transfer record is deleted by cascade
            transfer.delete(cleanRecordID(rec.id))
            g.db.commit()  # trigger the casscade delete of transactions
            rec = transfer.new()
            transfer.update(rec, request.form)

        transfer.save(rec)
        #Create trx recods for this transfer...
        #create the Outgoing trx record
        trx_rec = trx_table.new()

        trx_rec.item_id = rec.item_id
        trx_rec.qty = abs(rec.qty) * -1
        trx_rec.created = rec.transfer_date
        trx_rec.warehouse_id = request.form["warehouse_out_id"]
        trx_rec.value = 0
        trx_rec.trx_type = "Transfer Out"
        trx_table.save(trx_rec)
        rec.out_trx_id = trx_rec.id

        trx_rec2 = trx_table.new()

        trx_table.update(trx_rec2, trx_rec._asdict())
        trx_rec2.qty = abs(rec.qty)
        trx_rec2.value = Item(g.db).lifo_cost(trx_rec.item_id,
                                              end_date=rec.transfer_date)
        trx_rec2.warehouse_id = request.form["warehouse_in_id"]
        trx_rec2.trx_type = "Transfer In"
        trx_table.save(trx_rec2)
        rec.in_trx_id = trx_rec2.id

        transfer.save(rec)
        #Save some data to session
        session['last_transfer'] = {
            "transfer_date": rec.transfer_date,
        }

        try:
            g.db.commit()
            #Save the date and comment to session
            return True

        except Exception as e:
            flash(
                printException('Error attempting to save Transfer record',
                               str(e)))

    g.db.rollback()
    return False
コード例 #11
0
ファイル: user.py プロジェクト: wleddy/shotglass2
def register():
    """Allow people to sign up thier own accounts on the web site"""
    setExits()
    site_config = get_site_config()

    g.title = "Account Registration"
    g.editURL = url_for('.register')
    g.listURL = '/'  # incase user cancels
    user = User(g.db)
    rec = user.new()

    is_admin = False
    user_roles = None
    roles = None
    no_delete = True
    success = True
    help = render_markdown_for("new_account_help.md", mod)
    next = request.form.get('next', request.args.get('next', ''))

    # import pdb;pdb.set_trace()

    if 'confirm' in request.args:
        #Try to find the user record that requested registration
        rec = user.select_one(where='access_token = "{}"'.format(
            request.args.get('confirm', '')).strip())
        if rec and rec.access_token_expires > time():
            if site_config.get('ACTIVATE_USER_ON_CONFIRMATION', False):
                rec.active = 1
                user.save(rec, commit=True)
                # log the user in
                setUserStatus(rec.email, rec.id)

            if rec.active == 1:
                success = "active"
            else:
                success = "waiting"

            #inform the admins
            inform_admin_of_registration(rec)

            return render_template('registration_success.html',
                                   success=success,
                                   next=next)
        else:
            flash("That registration request has expired")
            return redirect('/')

    if request.form:
        #update the record
        user.update(rec, request.form)

        if validForm(rec):
            rec.active = 0  # Self registered accounts are inactive by default
            set_password_from_form(rec)
            set_username_from_form(rec)
            rec.access_token = get_access_token()
            rec.access_token_expires = time() + (3600 * 48)
            if site_config.get('AUTOMATICALLY_ACTIVATE_NEW_USERS', False):
                rec.active = 1
                success = "active"

            try:
                user.save(rec)

                # give user default roles
                for role in site_config.get('DEFAULT_USER_ROLES', ['user']):
                    User(g.db).add_role(rec.id, role)

                g.db.commit()
                # log the user in
                setUserStatus(rec.email, rec.id)

                #inform the admins
                inform_admin_of_registration(rec)

                #Send confirmation email to user if not already active
                full_name = '{} {}'.format(rec.first_name,
                                           rec.last_name).strip()
                to = [(full_name, rec.email)]
                context = {'rec': rec, 'confirmation_code': rec.access_token}
                subject = 'Please confirm your account registration at {}'.format(
                    site_config['SITE_NAME'])
                html_template = 'email/registration_confirm.html'
                text_template = 'email/registration_confirm.txt'
                if rec.active == 1:
                    subject = 'Your account is now active at {}'.format(
                        site_config['SITE_NAME'])
                    html_template = 'email/activation_complete.html'
                    text_template = 'email/activation_complete.txt'

                send_message(to,
                             context=context,
                             subject=subject,
                             html_template=html_template,
                             text_template=text_template)

            except Exception as e:
                g.db.rollback()
                mes = "An error occured while new user was attempting to register"
                printException(mes, "error", e)
                # Send email to the administrator
                to = [(site_config['MAIL_DEFAULT_SENDER'],
                       site_config['MAIL_DEFAULT_ADDR'])]
                context = {'mes': mes, 'rec': rec, 'e': str(e)}
                body = "Signup Error\n{{context.mes}}\n{{context.e}}\nrec:\n{{context.rec}}"
                send_message(to, context=context, body=body, subject=mes)
                success = False

            return render_template(
                'registration_success.html',
                success=success,
                next=next,
            )

    return render_template(
        'user_edit.html',
        rec=rec,
        no_delete=no_delete,
        is_admin=is_admin,
        next=next,
    )
コード例 #12
0
ファイル: user.py プロジェクト: wleddy/shotglass2
def edit(rec_handle=None):
    setExits()
    g.title = "Edit {} Record".format(g.title)
    #import pdb;pdb.set_trace()
    site_config = get_site_config()

    user = User(g.db)
    rec = None
    request_rec_id = cleanRecordID(
        request.form.get('id', request.args.get('id', -1)))
    is_admin = g.admin.has_access(g.user, User)
    no_delete = not is_admin
    new_password = ''
    confirm_password = ''
    user_roles = ['user']  # default

    #limit roles to roles <= current users rank
    curr_user_max_rank = user.max_role_rank(g.user)
    roles = Role(g.db).select(where="rank <= {}".format(curr_user_max_rank))

    include_inactive = True
    next = request.form.get('next', request.args.get('next', ''))

    if not is_admin:
        g.listURL = g.homeURL  # Non admins can't see the list
        include_inactive = False

    if rec_handle != None:
        pass  #rec_handle has to come from admin() at this point
    elif rec_handle == None and g.user != None and request_rec_id == -1:
        rec_handle = g.user
    else:
        rec_handle = request_rec_id
        if rec_handle < 0:
            flash("That is not a valid User ID")
            return redirect(g.listURL)

    if not request.form:
        """ if no form object, send the form page """
        if rec_handle != g.user and not is_admin:
            flash("You do not have access to that area")
            return redirect(g.homeURL)
        elif curr_user_max_rank < user.max_role_rank(rec_handle):
            flash(
                "You don't have sufficiant privelages to edit that user record."
            )
            return redirect(g.homeURL)
        elif rec_handle == 0:
            rec = user.new()
        else:
            rec = user.get(rec_handle, include_inactive=include_inactive)
            if not rec:
                flash("Unable to locate user record")
                return redirect('/')

            user_roles = get_user_role_names(rec)

    else:
        #have the request form
        # import pdb;pdb.set_trace()
        is_new_user = False
        if rec_handle and request.form['id'] != 'None':
            rec = user.get(rec_handle, include_inactive=include_inactive)
            user_roles = get_user_role_names(rec)
        else:
            # its a new unsaved record
            is_new_user = True
            rec = user.new()
            user.update(rec, request.form)

        if validForm(rec):

            #Are we editing the current user's record?
            editingCurrentUser = ''
            if (g.user == rec.username):
                if 'new_username' in request.form:
                    editingCurrentUser = request.form['new_username'].strip()
                else:
                    editingCurrentUser = g.user
            else:
                if (g.user == rec.email):
                    editingCurrentUser = request.form['email'].strip()

            #update the record
            user.update(rec, request.form)

            # ensure these are ints
            if 'may_send_email' in rec._fields:
                rec.may_send_email = cleanRecordID(rec.may_send_email)
            if 'may_send_text' in rec._fields:
                rec.may_send_text = cleanRecordID(rec.may_send_text)

            set_username_from_form(rec)
            set_password_from_form(rec)

            try:
                user.save(rec)

                # update the user roles
                if 'roles_select' in request.form:
                    # import pdb;pdb.set_trace()
                    #delete all the users current roles
                    user.clear_roles(rec.id)
                    for role_name in request.form.getlist('roles_select'):
                        #find the role by name
                        role = Role(g.db).select_one(
                            where='name = "{}"'.format(role_name))
                        if role:
                            user.add_role(rec.id, role.id)

                # if the username or email address are the same as g.user
                # update g.user if it changes
                if (editingCurrentUser != ''):
                    setUserStatus(editingCurrentUser, rec.id)

                g.db.commit()

            except Exception as e:
                g.db.rollback()
                flash(
                    printException(
                        'Error attempting to save ' + g.title + ' record.',
                        "error", e))
                return redirect(g.listURL)

            if is_new_user:
                rec.access_token = get_access_token()
                rec.access_token_expires = time() + (3600 * 48)

                #inform the admins
                inform_admin_of_registration(rec)

                # send an email to welcome the new user
                full_name = '{} {}'.format(rec.first_name,
                                           rec.last_name).strip()

                context = {
                    'rec': rec,
                    'full_name': full_name,
                }
                to_address_list = [(full_name, rec.email)]
                sent, msg = send_message(
                    to_address_list,
                    subject="Welcome to {{ site_config.SITE_NAME}}",
                    context=context,
                    html_template='email/welcome.html',
                    text_template='email/welcome.txt',
                )
                if not sent:
                    flash('The welcome message could not be sent. Error: {}'.
                          format(msg))

            return redirect(g.listURL)

        else:
            # form did not validate, give user the option to keep their old password if there was one
            #need to restore the username
            user.update(rec, request.form)
            if 'new_username' in request.form:
                rec.username = request.form[
                    'new_username']  #preserve user input
            # preserve the selected roles
            #import pdb;pdb.set_trace()
            if 'roles_select' in request.form:
                user_roles = request.form.getlist('roles_select')
            #and password
            new_password = request.form.get('new_password', '')
            confirm_password = request.form.get('confirm_password', '')

    # display form
    return render_template(
        'user_edit.html',
        rec=rec,
        no_delete=no_delete,
        is_admin=is_admin,
        next=next,
        user_roles=user_roles,
        roles=roles,
        new_password=new_password,
        confirm_password=confirm_password,
    )
コード例 #13
0
    def send(self):
        outgoing = Mail()

        sent_cnt = 0
        err_cnt = 0
        err_list = []
        result = True
        # import pdb;pdb.set_trace()
        if not self._to:
            self._to = [
                (self.admin_name, self.admin_addr),
            ]

        if not self.subject:
            self.subject = 'A message from {}'.format(self.from_sender).strip()
        self.subject = '{} {}'.format(self.subject_prefix,
                                      self.subject).strip()

        for recipient in self._to:
            name = ""
            address = ""
            body_err_head = ""
            if isinstance(recipient, tuple):
                if len(recipient) == 1:
                    # extend recipient
                    recipient = recipient[0] + (recipient[0], )
                name = recipient[0]
                address = recipient[1]
            else:
                address = recipient  #assume its a str
                name = recipient

            if not looksLikeEmailAddress(address) and looksLikeEmailAddress(
                    name):
                # swap values
                temp = address
                address = name
                name = temp
            if not looksLikeEmailAddress(address):
                # still not a good address...
                address = self.admin_addr
                name = self.admin_name
                if not self.body:
                    self.body = ""

                body_err_head = "**Bad Address**: {}\r\r".format(recipient, )

            # the subject line may contain jinja template code
            self.subject = render_template_string(self.subject.strip(),
                                                  **self.kwargs)

            message_dict = dict(
                subject=self.subject,
                sender=(self.from_sender, self.from_address),
                recipients=[(name, address)],
                cc=self._cc,
                bcc=self._bcc,
                reply_to=self.reply_to,
            )

            #Start a message
            if self.site_config.get('MAIL_USE_GMAIL_API', False):
                msg = GmailAPIMessage(**message_dict)
            else:
                msg = Message(**message_dict)

            #Get the text body verson
            if self.body:
                if self.body_is_html:
                    msg.html = render_template_string(
                        "{}{}".format(
                            body_err_head,
                            self.body,
                        ), **self.kwargs)
                else:
                    msg.body = render_template_string(
                        "{}{}".format(
                            body_err_head,
                            self.body,
                        ), **self.kwargs)
            if self.html_template:
                msg.html = render_template(self.html_template, **self.kwargs)
            if self.text_template:
                msg.body = render_template(self.text_template, **self.kwargs)
            if not msg.body and not msg.html:
                self._set_result(False, 'Message contained no body content.')
                return

            if self._attachments:
                for attachment in self._attachments:
                    if attachment and len(attachment) > 2:
                        msg.attach(attachment[0], attachment[1], attachment[2])

            try:
                outgoing.send(msg)
                sent_cnt += 1
            except Exception as e:
                mes = "Error Sending email"
                printException(mes, "error", e)
                err_cnt += 1
                err_list.append("Error sending message to {} err: {}".format(
                    recipient, str(e)))

        # End Loop
        if sent_cnt == 0:
            mes = "No messages were sent."
            result = False
        else:
            mes = "{} messages sent successfully.".format(sent_cnt)
        if err_cnt > 0:
            result = False
            mes = mes + " {} messages had errors.\r\r{}".format(
                err_cnt, err_list)

        self._set_result(result, mes)
コード例 #14
0
    def backup(self):
        """Create timestamped database copy"""

        try:
            # clear any previous errors
            self._set_result(0)

            # the data file exists
            if not os.path.isfile(self.database_path):
                self._set_result(10)
                mes = "The source file '{}' was not found.".format(
                    self.database_path)
                raise self.BackupFatalError(mes, self.result_code)

            if not os.path.isdir(self.backup_dir):
                #print('Creating Backup Directory')
                try:
                    os.makedirs(self.backup_dir)
                except Exception as e:
                    self._set_result(11)
                    mes = "Unable to access the backup diretory at '{}'.\r\rSystem error: {}".format(
                        self.backup_dir, str(e))
                    raise self.BackupFatalError(mes, self.result_code)

            # test to see if it's time for a backup
            # do this before checking for data change
            if not self._backup_time():
                self._set_result(1)  # too soon
                raise self.BackupSoftError(self.result, self.result_code)

            # get the hash from the last backup
            if not self.source_changed():
                self._set_result(2)  #not changed
                raise self.BackupSoftError(self.result, self.result_code)

            # The backup name will be <original file name>-<date and time>.sqlite
            backup_target = os.path.join(
                self.backup_dir,
                os.path.basename(self.database_path) +
                local_datetime_now().strftime("-%Y-%m-%d-%H-%M") + '.sqlite')
            # let's do it!
            try:
                connection = sqlite3.connect(self.database_path)
                cursor = connection.cursor()

                # Lock database before making a backup
                cursor.execute('begin immediate')
                # Make new backup file
                shutil.copyfile(self.database_path, backup_target)
                # print ("\nCreating {0}").format(os.path.basename(backup_file))
                # Unlock database
                connection.rollback()

                # rollup
                # self._rollup()

                # purge old
                self._purge()

            except Exception as e:
                self._set_result(12)
                self.result += " at {} Err: {}".format(self.backup_dir, str(e))
                raise e

        except self.BackupSoftError:
            # not reallly an error. there is nothing to backup
            # The function that raised this error should have set self.result_code
            if self.result_code == 0:
                self._set_result(3)
            pass

        except self.BackupFatalError as e:
            # Something auful happened
            if not self.fatal_error:
                self._set_result(13)
            self.result = printException(str(e), err=e)

        except Exception as e:
            # some unexpected exception...
            self._set_result(20)
            mes = "An unexpected error occurred during backup"
            self.result += '\r\r' + printException(mes, err=e)

        return
コード例 #15
0
ファイル: item.py プロジェクト: wleddy/inventory
def edit(id=None):
    setExits()
    g.title = "Edit {} Record".format(g.title)

    item = Item(g.db)
    transactionList = None
    #import pdb;pdb.set_trace()
    if request.form:
        id = request.form.get('id', None)

    id = cleanRecordID(id)

    if id < 0:
        flash("Invalid Record ID")
        return redirect(g.listURL)

    categories = Category(g.db).select()
    uoms = Uom(g.db).select()

    if id >= 0 and not request.form:
        if id == 0:
            rec = item.new()  # allow creation of new properties
            item.save(rec)  # need an id for transactions
            g.db.commit()  # have to commit this to protect the ID we just got
            # This name changes behavure of the Cancel link in the edit form
            g.cancelURL = url_for('.cancel') + "{}/".format(rec.id)

        else:
            rec = item.get(id)

        if not rec:
            flash('Record not Found')
            return redirect(g.listURL)

    #import pdb;pdb.set_trace()

    if request.form:
        rec = item.get(id)
        if rec:
            item.update(rec, request.form)
            if validate_form():
                item.save(rec)
                try:
                    g.db.commit()
                    return redirect(g.listURL)

                except Exception as e:
                    g.db.rollback()
                    flash(
                        printException('Error attempting to save Item record',
                                       str(e)))
                    return redirect(g.listURL)
            else:
                pass  # There are imput errors

        else:
            flash('Record not Found')
            return redirect(g.listURL)

    transactionList = get_trx_list_for_item(rec.id)
    transferList = get_transfer_list_for_item(rec.id)
    qoh_list = get_qoh_by_warehouse(rec.id)
    on_hand = item.stock_on_hand(id)

    return render_template('item_edit.html',
                           rec=rec,
                           categories=categories,
                           uoms=uoms,
                           transactionList=transactionList,
                           transferList=transferList,
                           qoh_list=qoh_list,
                           on_hand=on_hand)
コード例 #16
0
ファイル: role.py プロジェクト: wleddy/shotglass2
def edit(rec_id=None):
    setExits()
    g.title = "Edit {} Record".format(g.title)

    role = PRIMARY_TABLE(g.db)
    rec = None
    super_user = User(g.db).user_has_role(session['user_id'], 'Super')
    no_delete = False

    rec_id = cleanRecordID(request.form.get('id', rec_id))

    if rec_id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    if not request.form:
        """ if no form object, send the form page """
        if rec_id == 0:
            rec = role.new()
        else:
            rec = role.get(rec_id)
            if not rec:
                flash("Unable to locate that record")
                return redirect(g.listURL)
    else:
        #have the request form
        if rec_id and request.form['id'] != 'None':
            rec = role.get(rec_id)
        else:
            # its a new unsaved record
            # import pdb;pdb.set_trace()
            rec = role.new()
            role.update(rec, request.form)

        if validForm(rec):
            #update the record
            # import pdb;pdb.set_trace()
            # set default for locked
            rec.locked = 0
            role.update(rec, request.form)
            if request.form.get('locked'):
                rec.locked = 1

            try:
                role.save(rec)
                g.db.commit()
            except Exception as e:
                g.db.rollback()
                flash(
                    printException(
                        'Error attempting to save ' + g.title + ' record.',
                        "error", e))

            return redirect(g.listURL)

        else:
            # form did not validate
            pass

    if rec and rec.locked and not super_user:
        no_delete = True

    # display form
    return render_template('role_edit.html',
                           rec=rec,
                           super_user=super_user,
                           no_delete=no_delete)
コード例 #17
0
ファイル: home.py プロジェクト: wleddy/shotglass2
def contact(**kwargs):
    """Send an email to the administator or contact specified.
    
    kwargs:
    
        to_addr: the address to send to
        
        to_contact: Name of contact
        
        subject: The email subject text
        
        custom_message: Message to display at top of contact form. should be html
        
        html_template: The template to use for the contact form
    
    """
    setExits()
    g.title = 'Contact Us'
    from shotglass2.shotglass import get_site_config
    from shotglass2.takeabeltof.mailer import send_message

    #import pdb;pdb.set_trace()

    site_config = get_site_config()
    show_form = True
    context = {}
    success = True
    bcc = None
    passed_quiz = False
    mes = "No errors yet..."
    to = []

    if not kwargs and request.form and 'kwargs' in request.form:
        kwargs = json.loads(request.form.get('kwargs', '{}'))

    subject = kwargs.get('subject',
                         "Contact from {}".format(site_config['SITE_NAME']))
    html_template = kwargs.get('html_template',
                               "home/email/contact_email.html")
    to_addr = kwargs.get('to_addr')
    to_contact = kwargs.get('to_contact', to_addr)
    custom_message = kwargs.get('custom_message')
    if to_addr:
        to.append((to_contact, to_addr))

    if custom_message:
        rendered_html = custom_message
    else:
        rendered_html = render_markdown_for('contact.md', mod)

    if request.form:
        quiz_answer = request.form.get('quiz_answer', "A")
        if quiz_answer.upper() == "C":
            passed_quiz = True
        else:
            flash("You did not answer the quiz correctly.")
        if request.form['email'] and request.form['comment'] and passed_quiz:
            context.update({'date': datetime_as_string()})
            for key, value in request.form.items():
                context.update({key: value})

            # get best contact email
            if not to:
                # See if the contact info is in Prefs
                try:
                    from shotglass2.users.views.pref import get_contact_email
                    contact_to = get_contact_email()
                    # contact_to may be a tuple, a list or None
                    if contact_to:
                        if not isinstance(contact_to, list):
                            contact_to = [contact_to]
                        to.extend(contact_to)

                except Exception as e:
                    printException(
                        "Need to update home.contact to find contacts in prefs.",
                        "error", e)

                try:
                    if not to:
                        to = [
                            (
                                site_config['CONTACT_NAME'],
                                site_config['CONTACT_EMAIL_ADDR'],
                            ),
                        ]
                    if site_config['CC_ADMIN_ON_CONTACT'] and site_config[
                            'ADMIN_EMAILS']:
                        bcc = site_config['ADMIN_EMAILS']

                except KeyError as e:
                    mes = "Could not get email addresses."
                    mes = printException(mes, "error", e)
                    if to:
                        #we have at least a to address, so continue
                        pass
                    else:
                        success = False

            if success:
                # Ok so far... Try to send
                success, mes = send_message(
                    to,
                    subject=subject,
                    html_template=html_template,
                    context=context,
                    reply_to=request.form['email'],
                    bcc=bcc,
                    custom_message=custom_message,
                    kwargs=kwargs,
                )

            show_form = False
        else:
            context = request.form
            flash('You left some stuff out.')

    if success:
        return render_template(
            'contact.html',
            rendered_html=rendered_html,
            show_form=show_form,
            context=context,
            passed_quiz=passed_quiz,
            kwargs=kwargs,
        )

    handle_request_error(mes, request)
    flash(mes)
    return render_template('500.html'), 500
コード例 #18
0
def contact():
    setExits()
    g.title = 'Contact Us'
    from shotglass2.shotglass import get_site_config
    from shotglass2.takeabeltof.mailer import send_message
    rendered_html = render_markdown_for('contact.md',mod)
    
    show_form = True
    context = {}
    success = True
    bcc=None
    passed_quiz = False
    site_config = get_site_config()
    mes = "No errors yet..."
    if request.form:
        #import pdb;pdb.set_trace()
        quiz_answer = request.form.get('quiz_answer',"A")
        if quiz_answer.upper() == "C":
            passed_quiz = True
        else:
            flash("You did not answer the quiz correctly.")
        if request.form['email'] and request.form['comment'] and passed_quiz:
            context.update({'date':datetime_as_string()})
            for key, value in request.form.items():
                context.update({key:value})
                
            # get best contact email
            to = []
            # See if the contact info is in Prefs
            try:
                from shotglass2.users.views.pref import get_contact_email
                contact_to = get_contact_email()
                if contact_to:
                    to.append(contact_to)
            except Exception as e:
                printException("Need to update home.contact to find contacts in prefs.","error",e)
                
            try:
                if not to:
                    to = [(site_config['CONTACT_NAME'],site_config['CONTACT_EMAIL_ADDR'],),]
                if site_config['CC_ADMIN_ON_CONTACT'] and site_config['ADMIN_EMAILS']:
                    bcc = site_config['ADMIN_EMAILS']
                
            except KeyError as e:
                mes = "Could not get email addresses."
                mes = printException(mes,"error",e)
                if to:
                    #we have at least a to address, so continue
                    pass
                else:
                    success = False
                    
            if success:
                # Ok so far... Try to send
                success, mes = send_message(
                                    to,
                                    subject = "Contact from {}".format(site_config['SITE_NAME']),
                                    html_template = "home/email/contact_email.html",
                                    context = context,
                                    reply_to = request.form['email'],
                                    bcc=bcc,
                                )
        
            show_form = False
        else:
            context = request.form
            flash('You left some stuff out.')
            
    if success:
        return render_template('contact.html',rendered_html=rendered_html, show_form=show_form, context=context,passed_quiz=passed_quiz)
            
    handle_request_error(mes,request,500)
    flash(mes)
    return render_template('500.html'), 500
コード例 #19
0
def edit(rec_id=None):
    setExits()
    g.title = "Edit {} Record".format(g.title)

    pref = Pref(g.db)
    rec = None

    if rec_id == None:
        rec_id = request.form.get('id', request.args.get('id', -1))

    rec_id = cleanRecordID(rec_id)
    #import pdb;pdb.set_trace

    if rec_id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    if not request.form:
        """ if no form object, send the form page """
        if rec_id == 0:
            rec = pref.new()
        else:
            rec = pref.get(rec_id)
            if not rec:
                flash("Unable to locate that record")
                return redirect(g.listURL)
    else:
        #have the request form
        #import pdb;pdb.set_trace()
        if rec_id and request.form['id'] != 'None':
            rec = pref.get(rec_id)
        else:
            # its a new unsaved record
            rec = pref.new()
            pref.update(rec, request.form)

        if validForm(rec):
            #update the record
            #import pdb;pdb.set_trace()

            pref.update(rec, request.form)
            # make names lower case
            if rec.user_name.strip() == '':
                rec.user_name = None
            if rec.expires and rec.expires.strip().lower() == 'never':
                rec.expires = None

            try:
                pref.save(rec)
                g.db.commit()
            except Exception as e:
                g.db.rollback()
                flash(
                    printException(
                        'Error attempting to save ' + g.title + ' record.',
                        "error", e))

            return redirect(g.listURL)

        else:
            # form did not validate
            pass

    # display form
    return render_template('pref_edit.html', rec=rec)