def wrap(*args, **kwargs): self = args[0] try: return fn(*args, **kwargs) except NoResultFound as e: print('route_except_handler(): NoResultFound exception:\n',\ e, file=sys.stderr) self.set_status(404) session = Session() try: page = session.query(StaticPageModel)\ .filter_by(alias=_404_page_alias).one() except Exception as e: session.close() print('route_except_handler(): cannot get 404 page'+\ ' by "%s" alias:\n' % str(_404_page_alias),\ e, file=sys.stderr) self.set_status(500) return self.write('500: Internal server error') session.close() menu = self.getmenu() data = page.to_frontend data.update({ 'is_catalog': False, 'is_catalog_item': False, 'menu': menu, 'is_debug': config('DEBUG') }) data.update(self.get_nonrel_handlers()) data.update(self.get_helpers()) return self.render('client/error-404.jade', **data) except Exception as e: print(e, file=sys.stderr) self.set_status(500) return self.write('500: Internal server error')
def get(self, alias, suffix): session = Session() alias = '/' + alias + suffix try: page = session\ .query(StaticPageModel)\ .filter_by(alias=alias, is_active=True)\ .one() except Exception as e: session.close() print('StaticPageRoute.get(): cannot get static page or page is not active'+\ ' by "%s" alias:\n' % str(alias), e, file=sys.stderr) raise e session.close() menu = self.getmenu(page_alias=alias) data = page.to_frontend data.update({ 'is_catalog': False, 'is_catalog_item': False, 'menu': menu, 'is_debug': config('DEBUG') }) data.update(self.get_nonrel_handlers()) data.update(self.get_helpers()) return self.render('client/content-page.jade', **data)
def get(self): data = {'is_debug': config('DEBUG')} urls = [] session = Session() try: pages = session.query(StaticPageModel)\ .filter_by(is_active=True)\ .order_by(StaticPageModel.id.asc()).all() sections = session.query(CatalogSectionModel)\ .filter_by(is_active=True)\ .order_by(CatalogSectionModel.id.asc()).all() items = session.query(CatalogItemModel)\ .filter_by(is_active=True)\ .order_by(CatalogItemModel.id.asc()).all() except Exception as e: session.close() print('SiteMapRoute.get(): cannot get data from DB:\n',\ e, file=sys.stderr) raise e session.close() for page in [x.item for x in pages]: if '404' in page['alias']: continue urls.append({ 'alias': quote(page['alias'], encoding='utf-8'), 'lastmod': page['last_change'] }) for section in [x.item for x in sections]: url = '/catalog/{0}.html'.format(section['alias']) url = quote(url, encoding='utf-8') urls.append({ 'alias': url, 'lastmod': section['last_change'] }) for item in [x.item for x in items]: section_alias = None for section in [x.item for x in sections]: if section['id'] == item['section_id']: section_alias = section['alias'] if section_alias is None: e = Exception('SiteMapRoute: '+\ 'cannot find section for element #%d' % item['id']) print(e, file=sys.stderr) continue url = '/catalog/{0}/{1}.html'.format(section_alias, item['alias']) url = quote(url, encoding='utf-8') urls.append({ 'alias': url, 'lastmod': section['last_change'] }) data.update({'urls': tuple(urls)}) self.set_header('Content-Type', 'text/xml; charset="utf-8"') return self.render('client/sitemap.jade', **data)
def post(self): if not self.get_current_user(): self.set_status(403) return self.json_response({ 'status': 'unauthorized' }) file_path = config('UPLOAD_FILES_PATH') hashes = [] for f in self.request.files.items(): _file = f[1][0] _filename = hashlib.sha512( str(time.time()).encode('utf-8')).hexdigest()[0:35] fname = _filename + '.' + _file['content_type'].split('/')[1] f = open(os.path.join(file_path, fname), 'wb') f.write(_file['body']) f.close() hashes.append({'name': fname}) return self.json_response({ 'status': 'success', 'files': hashes })
def get_json_localization(side): pathc = config('LOCALIZATION')['SOURCES'] if side is None and not pathc[side]: raise Exception("Incorrect localization source") f = open(os.path.join(os.getcwd(), pathc[side]), 'r') jn = json.loads(''.join([line for line in f])) f.close() return jn
def get(self, category, item): session = Session() # check for active element section try: section = session.query(CatalogSectionModel)\ .filter_by(alias=category, is_active=True)\ .one() except Exception as e: session.close() print('CatalogItemRoute.get(): cannot get catalog section or section is not active'+\ ' by "%s" code:\n' % str(category),\ e, file=sys.stderr) raise e if item.endswith(".html"): item = item.replace('.html', '').replace('/', '') # get item try: page = session\ .query(CatalogItemModel)\ .filter_by(alias=item, is_active=True)\ .one() except Exception as e: session.close() print('CatalogItemRoute.get(): cannot get catalog item or item is not active'+\ ' by "%s" code:\n' % str(item),\ e, file=sys.stderr) raise e session.close() data = page.to_frontend # check for category if data['section_id'] != section.to_frontend['id']: e = NoResultFound() print('CatalogItemRoute.get(): mismatch catalog category of element and category in URL'+\ ' by "%s" code:\n' % str(item),\ e, file=sys.stderr) raise e menu = self.getmenu( catalog_section_alias=category, catalog_item_alias=item) data.update({ 'is_catalog': True, 'is_catalog_item': True, 'catalog_item_id': data['id'], 'is_main_page': False, 'menu': menu, 'is_debug': config('DEBUG') }) data.update(self.get_nonrel_handlers()) data.update(self.get_helpers()) return self.render('client/catalog-detail.jade', **data)
def get(self, category, item): session = Session() # check for active element section try: section = session.query(CatalogSectionModel)\ .filter_by(alias=category, is_active=True)\ .one() except Exception as e: session.close() print('CatalogItemRoute.get(): cannot get catalog section or section is not active'+\ ' by "%s" code:\n' % str(category),\ e, file=sys.stderr) raise e if item.endswith(".html"): item = item.replace('.html', '').replace('/', '') # get item try: page = session\ .query(CatalogItemModel)\ .filter_by(alias=item, is_active=True)\ .one() except Exception as e: session.close() print('CatalogItemRoute.get(): cannot get catalog item or item is not active'+\ ' by "%s" code:\n' % str(item),\ e, file=sys.stderr) raise e session.close() data = page.to_frontend # check for category if data['section_id'] != section.to_frontend['id']: e = NoResultFound() print('CatalogItemRoute.get(): mismatch catalog category of element and category in URL'+\ ' by "%s" code:\n' % str(item),\ e, file=sys.stderr) raise e menu = self.getmenu(catalog_section_alias=category, catalog_item_alias=item) data.update({ 'is_catalog': True, 'is_catalog_item': True, 'catalog_item_id': data['id'], 'is_main_page': False, 'menu': menu, 'is_debug': config('DEBUG') }) data.update(self.get_nonrel_handlers()) data.update(self.get_helpers()) return self.render('client/catalog-detail.jade', **data)
def get(self): data = {'is_debug': config('DEBUG')} urls = [] session = Session() try: pages = session.query(StaticPageModel)\ .filter_by(is_active=True)\ .order_by(StaticPageModel.id.asc()).all() sections = session.query(CatalogSectionModel)\ .filter_by(is_active=True)\ .order_by(CatalogSectionModel.id.asc()).all() items = session.query(CatalogItemModel)\ .filter_by(is_active=True)\ .order_by(CatalogItemModel.id.asc()).all() except Exception as e: session.close() print('SiteMapRoute.get(): cannot get data from DB:\n',\ e, file=sys.stderr) raise e session.close() for page in [x.item for x in pages]: if '404' in page['alias']: continue urls.append({ 'alias': quote(page['alias'], encoding='utf-8'), 'lastmod': page['last_change'] }) for section in [x.item for x in sections]: url = '/catalog/{0}.html'.format(section['alias']) url = quote(url, encoding='utf-8') urls.append({'alias': url, 'lastmod': section['last_change']}) for item in [x.item for x in items]: section_alias = None for section in [x.item for x in sections]: if section['id'] == item['section_id']: section_alias = section['alias'] if section_alias is None: e = Exception('SiteMapRoute: '+\ 'cannot find section for element #%d' % item['id']) print(e, file=sys.stderr) continue url = '/catalog/{0}/{1}.html'.format(section_alias, item['alias']) url = quote(url, encoding='utf-8') urls.append({'alias': url, 'lastmod': section['last_change']}) data.update({'urls': tuple(urls)}) self.set_header('Content-Type', 'text/xml; charset="utf-8"') return self.render('client/sitemap.jade', **data)
def get(self, *args): lang = config('LOCALIZATION')['LANG'] localization = get_json_localization('ADMIN')[lang] kwrgs = { 'page_title': localization['page_title'], 'lang': lang, 'local': localization, 'is_auth': ( lambda: 1 if self.get_current_user() else 0)(), 'is_debug': ( lambda: 1 \ if self.application.settings.get('debug') \ else 0)() } return self.render('admin/layout.jade', **kwrgs)
def send_mail(msg=None, theme=None): mailc = config('MAIL') from_addr = mailc['FROM_ADDRESS'] to = mailc['MAIN_RECIPIENT'] user = mailc['USER'] pwd = mailc['PASS'] smtpserver = smtplib.SMTP(mailc['SMTP_PROVIDER']['HOST'], mailc['SMTP_PROVIDER']['PORT']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(user, pwd) body = ''.join("Content-Type: text/html; charset=utf-8\r\n" + "From: %s\r\n" % from_addr + "To: %s\r\n" % to + "Subject: %s\r\n" % theme + "\r\n" + msg + "\r\n") smtpserver.sendmail(user, to, body.encode('utf-8')) smtpserver.close()
def post(self): if not self.get_current_user(): self.set_status(403) return self.json_response({'status': 'unauthorized'}) file_path = config('UPLOAD_FILES_PATH') hashes = [] for f in self.request.files.items(): _file = f[1][0] _filename = hashlib.sha512(str( time.time()).encode('utf-8')).hexdigest()[0:35] fname = _filename + '.' + _file['content_type'].split('/')[1] f = open(os.path.join(file_path, fname), 'wb') f.write(_file['body']) f.close() hashes.append({'name': fname}) return self.json_response({'status': 'success', 'files': hashes})
def get(self, alias): session = Session() if alias.endswith(".html"): alias = alias.replace('.html', '').replace('/', '') try: page = session.query(CatalogSectionModel)\ .filter_by(alias=alias, is_active=True)\ .one() except Exception as e: session.close() print('CatalogSectionRoute.get(): cannot get catalog section or section is not active'+\ ' by "%s" code:\n' % str(alias),\ e, file=sys.stderr) raise e try: items = session.query(CatalogItemModel)\ .filter_by(section_id=page.id, is_active=True)\ .order_by(CatalogItemModel.id.asc()).all() except Exception as e: session.close() print('CatalogSectionRoute.get(): cannot get catalog items'+\ ' by section #%d:\n' % int(page.id),\ e, file=sys.stderr) raise e session.close() menu = self.getmenu(catalog_section_alias=alias) data = page.to_frontend data.update({ 'is_catalog': True, 'is_catalog_item': False, 'is_main_page': False, 'items': [x.to_frontend for x in items], 'menu': menu, 'is_debug': config('DEBUG') }) data.update(self.get_nonrel_handlers()) data.update(self.get_helpers()) return self.render('client/catalog-sections.jade', **data)
def send_mail(msg=None, theme=None): mailc = config('MAIL') from_addr = mailc['FROM_ADDRESS'] to = mailc['MAIN_RECIPIENT'] user = mailc['USER'] pwd = mailc['PASS'] smtpserver = smtplib.SMTP( mailc['SMTP_PROVIDER']['HOST'], mailc['SMTP_PROVIDER']['PORT']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(user, pwd) body = ''.join( "Content-Type: text/html; charset=utf-8\r\n" + "From: %s\r\n" % from_addr + "To: %s\r\n" % to + "Subject: %s\r\n" % theme + "\r\n" + msg + "\r\n" ) smtpserver.sendmail(user, to, body.encode('utf-8')) smtpserver.close()
def get(self): session = Session() try: page = session\ .query(StaticPageModel)\ .filter_by(alias='/', is_active=True)\ .one() except Exception as e: session.close() print('MainRoute.get(): cannot get main page:\n', e, file=sys.stderr) raise e session.close() menu = self.getmenu(page_alias='/') data = page.to_frontend data.update({ 'is_catalog': False, 'is_catalog_item': False, 'menu': menu, 'is_debug': config('DEBUG') }) data.update(self.get_nonrel_handlers()) data.update(self.get_helpers()) return self.render('client/content-page.jade', **data)
def post(self): is_ajax = False lang = config('LOCALIZATION')['LANG'] localization = get_json_localization('CLIENT')[lang]['forms'] actions = { 'call' : { 'fn': self.save_call, }, 'order' : { 'fn': self.save_order, } } try: is_ajax = self.get_argument('ajax') except MissingArgumentError: pass args = dict([ x.split('=') for x in str(self.request.body).split('&') if 'action' not in x ]) for key in args: args[key] = self.get_argument(key) action = self.get_argument('action') if action not in actions.keys(): if is_ajax: self.set_status(400) return self.json_response({'status': 'unknown_form'}) return self.write("Lol, request isn't correct") p_title = localization['response_page'][action] fn = actions[action]['fn'] errors = self.validate_fields(args) if len(errors) == 0: try: fn(args) except Exception as e: print('FormsHandler.post(): post form data error:\n',\ e, file=sys.stderr) self.set_status(500) return self.json_response({'status': 'system_fail'})\ if is_ajax\ else self.write('Internal server Error') if is_ajax: return self.json_response({'status': 'success'}) kwrgs = self.set_kwargs( success_msg_list=['success'], # TODO :: messages! title=p_title) return self.render('client/content-page.jade', **kwargs) else: if is_ajax: self.set_status(400) self.json_response({ 'status': 'error', 'error_fields': { x: 'required' for x in errors } }) else: err_list = [localization['err']['required_page'].format(localization['fields'][x]) \ for x in errors ] kwrgs = self.set_kwargs( error_msg_list=err_list, title=p_title) self.render('client/content-page.jade', **kwrgs)
def get(self): data = {'is_debug': config('DEBUG')} self.set_header('Content-Type', 'text/plain; charset="utf-8"') data.update(self.get_nonrel_handlers()) return self.render('client/robots.jade', **data)
# -*- coding: utf-8 -*- __all__ = ['base', 'catalog', 'decorators', 'main', 'robots', 'sitemap'] from pyjade.ext.tornado import patch_tornado patch_tornado() from tornado.web import StaticFileHandler import os from app.configparser import config from .main import (MainRoute, StaticPageRoute, FormsHandler) from .catalog import (CatalogItemRoute, CatalogSectionRoute) from .robots import RobotsTxtRoute from .sitemap import SiteMapRoute routes = [('/', MainRoute), ('/uploaded-files/(.*)', StaticFileHandler, { "path": os.path.join(os.getcwd(), config('UPLOAD_FILES_PATH')) }), ('/api/forms/', FormsHandler), ('/catalog/(.*?)/(.*?)\.html', CatalogItemRoute), ('/catalog/(.*?)\.html', CatalogSectionRoute), ('/robots\.txt', RobotsTxtRoute), ('/sitemap.xml', SiteMapRoute), ('/(.*?)(\.html)', StaticPageRoute), ('/(.*?)()', StaticPageRoute)]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, sys import getopt from app.configparser import config from app.app import run_instance from app.models.init_models import init_models from app.models.usermodels import create_init_user import multiprocessing devserver = config('DEV_SERVER') prserver = config('PRODUCTION_SERVER') def error_handler(fn): pass def devserver(port=devserver['PORT'], host=devserver['HOST']): run_instance(port, host) def server(instances=prserver['INSTANCES']): port = prserver['MAIN_PORT'] host = prserver['HOST'] for ins in range(prserver['INSTANCES']): process = multiprocessing.Process(target=run_instance, args=(port + ins, host)) process.start()
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from app.configparser import config from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import inspect Base = declarative_base() dbprefix = config('DATABASE')['TABLE_NAME_PREFIX'] dbc = config('DATABASE') engine = create_engine("postgresql://%s:%s@%s/%s" % (dbc['USER'], dbc['PASS'], dbc['HOST'], dbc['DBNAME'])) db_inspector = inspect(engine) Session = sessionmaker(bind=engine)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, sys import getopt from app.configparser import config from app.app import run_instance from app.models.init_models import init_models from app.models.usermodels import create_init_user import multiprocessing devserver = config('DEV_SERVER') prserver = config('PRODUCTION_SERVER') def error_handler(fn): pass def devserver(port=devserver['PORT'], host=devserver['HOST']): run_instance(port, host) def server(instances=prserver['INSTANCES']): port = prserver['MAIN_PORT'] host = prserver['HOST'] for ins in range(prserver['INSTANCES']): process = multiprocessing.Process(target=run_instance, args=(port + ins, host)) process.start() def dbsync(): try:
patch_tornado() from tornado.web import StaticFileHandler import os from app.configparser import config from .main import ( MainRoute, StaticPageRoute, FormsHandler ) from .catalog import (CatalogItemRoute, CatalogSectionRoute) from .robots import RobotsTxtRoute from .sitemap import SiteMapRoute routes = [ ('/', MainRoute), ('/uploaded-files/(.*)', StaticFileHandler, {"path": os.path.join(os.getcwd(), config('UPLOAD_FILES_PATH'))}), ('/api/forms/', FormsHandler), ('/catalog/(.*?)/(.*?)\.html', CatalogItemRoute), ('/catalog/(.*?)\.html', CatalogSectionRoute), ('/robots\.txt', RobotsTxtRoute), ('/sitemap.xml', SiteMapRoute), ('/(.*?)(\.html)', StaticPageRoute), ('/(.*?)()', StaticPageRoute) ]
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from app.configparser import config from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import inspect Base = declarative_base() dbprefix = config('DATABASE')['TABLE_NAME_PREFIX'] dbc = config('DATABASE') engine = create_engine("postgresql://%s:%s@%s/%s" % ( dbc['USER'], dbc['PASS'], dbc['HOST'], dbc['DBNAME'])) db_inspector = inspect(engine) Session = sessionmaker(bind=engine)