def test_render_markdown_for(): with app.app_context(): from flask import Blueprint, g from shotglass2 import shotglass shotglass.set_template_dirs(app) mod = Blueprint('testme',__name__) result = utils.render_markdown_for('test_script.md',mod) assert "no file found" in result result = utils.render_markdown_for('takeabeltof.md',mod) assert "no file found" not in result assert "<h1>Takeabeltof</h1>" in result
def about(): setExits() g.title = "About" rendered_html = render_markdown_for('about.md',mod) return render_template('about.html',rendered_html=rendered_html)
def docs(filename=None): #setExits() g.title = "Docs" from shotglass2.shotglass import get_site_config site_config = get_site_config() #import pdb;pdb.set_trace() file_exists = False if not filename: filename = "README.md" else: filename = filename.strip('/') # first try to get it as a (possibly) valid path temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),filename) if not os.path.isfile(temp_path): # try the default doc dir temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),'docs',filename) if not os.path.isfile(temp_path) and 'DOC_DIRECTORY_LIST' in site_config: for path in site_config['DOC_DIRECTORY_LIST']: temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),path.strip('/'),filename) if os.path.isfile(temp_path): break filename = temp_path file_exists = os.path.isfile(filename) if file_exists: rendered_html = render_markdown_for(filename,mod) return render_template('markdown.html',rendered_html=rendered_html) else: #file not found return abort(404)
def home(): setExits() g.title = 'Home' g.suppress_page_header = True rendered_html = render_markdown_for('index.md', mod) return render_template( 'index.html', rendered_html=rendered_html, )
def render_for(filename=None): """ The idea is to create a mechanism to serve simple files without having to modify the www.home module create url as {{ url_for('www.render_for', filename='<name of template>' ) }} filename must not have an extension. First see if a file ending in the extension .md or .html exists in the /templates/www directroy and serve that if found. markdown files will be rendered in the markdown.html template. html files will be rendered as a normal freestanding template. """ # templates for this function can only be in the root tempalate/www directory temp_path = 'templates/www' path = None if filename: for extension in [ 'md', 'html', ]: file_loc = os.path.join(os.path.dirname(os.path.abspath(__name__)), temp_path, filename + '.' + extension) if os.path.isfile(file_loc): path = file_loc break else: pass if path: setExits() g.title = filename.replace('_', ' ').title() if extension == 'md': # use the markdown.html default path #rendered_html = render_markdown_for(path) return render_template('markdown.html', rendered_html=render_markdown_for(path)) else: # use the standard layout.html template return render_template(filename + '.html') else: return abort(404)
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
def render_page(markdown_source): rendered_html = render_markdown_for(markdown_source,mod) return render_template('markdown.html',rendered_html=rendered_html)
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, )
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