Exemple #1
0
class DataFormUpdate(Resource):
    api = AppInfo.get_api("ui")

    @api.doc(parser=create_parser())
    def get(self, table, id):
        try:
            create_parser().parse_args()
            context = g.context

            table_meta = read_table_meta(context, alias=table)
            solution_id = table_meta['solution_id']

            if solution_id == 1:
                file = f"templates/{table}_update.htm"
            else:
                file = f"solutions/{solution_id}/{table}_update.htm"

            fetch = build_fetchxml_by_alias(context, table, id, type="select")
            fetchparser = FetchXmlParser(fetch, context)
            rs = DatabaseServices.exec(fetchparser, context, fetch_mode=1)
            if rs.get_result() == None:
                abort(404, "Item not found => %s" % id)
            #
            # render the defined jinja template (in case ofahtm file)
            #
            logger.info(f"Redirect : {next}")

            template = JinjaTemplate.create_file_template(context, file)
            response = make_response(
                template.render({
                    "table": table,
                    "pagemode": "dataformupdate",
                    "id": id,
                    "data": rs.get_result(),
                    "context": context
                }))
            response.headers['content-type'] = 'text/html'

            return response

        except ConfigNotValid as err:
            logger.exception(f"Config not valid {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)
        except jinja2.exceptions.TemplateNotFound as err:
            logger.exception(f"TemplateNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(
                    context, 404, f"Template not found {err}"), 404)
        except FileNotFoundError as err:
            logger.exception(f"FileNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 404,
                                                     f"File not found {err}"),
                404)
        except RestApiNotAllowed as err:
            logger.exception(f"RestApiNotAllowed Exception: {err}")
            #return redirect(f"/auth/login.htm?redirect=/{path}", code=302)
            return redirect(f"/ui/login?redirect={request.url}", code=302)
        except Exception as err:
            logger.exception(f"Exception: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)
Exemple #2
0
class EntityList(Resource):
    api = AppInfo.get_api("ui")

    @api.doc(parser=create_parser())
    def get(self, table, view="default"):
        try:
            parser = create_parser().parse_args()
            context = g.context

            logger.info(f"app_id: {request.url}")
            file = f"templates/base/datalist.htm"
            query = "%"
            if 'query' in request.args:
                query = f"%{request.args.get('query')}%"

            table_meta = read_table_meta(context, alias=table)
            view_meta = read_table_view_meta(context, table_meta['id'], view,
                                             'LISTVIEW')

            fetch = view_meta['fetch_xml']
            #columns=json.loads(view_meta['col_definition'])

            fetch = fetch.replace("$$query$$", query)

            fetchparser = FetchXmlParser(fetch, context)
            rs = DatabaseServices.exec(fetchparser, context, fetch_mode=0)

            template = JinjaTemplate.create_file_template(context, file)
            response = make_response(
                template.render({
                    "data": rs.get_result(),
                    "columns": fetchparser.get_columns(),
                    "table": table,
                    "table_meta": table_meta,
                    "view_meta": view_meta,
                    "pagemode": "dataformlist",
                    "context": context
                }))

            response.headers['content-type'] = 'text/html'

            return response

        except ConfigNotValid as err:
            logger.exception(f"Config not valid {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)
        except DataViewNotFound as err:
            logger.exception(f"Dataview on api_table_view not found: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500,
                                                     "Dataview not found!"),
                500)
        except jinja2.exceptions.TemplateNotFound as err:
            logger.exception(f"TemplateNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(
                    context, 404, f"Template not found {err}"), 404)
        except FileNotFoundError as err:
            logger.exception(f"FileNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 404,
                                                     f"File not found {err}"),
                404)
        except RestApiNotAllowed as err:
            logger.exception(f"RestApiNotAllowed Exception: {err}")
            #return redirect(f"/ui/login?redirect=/ui/v1.0/data/view/{table}/default", code=302)
            return redirect(f"/ui/login?redirect={request.url}", code=302)
        except Exception as err:
            logger.exception(f"Exception: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)
Exemple #3
0
class Entity(Resource):
    api=AppInfo.get_api()

    @api.doc(parser=create_parser_delete())
    def delete(self,table,id):
        try:
            create_parser_delete().parse_args()
            context=g.context
            fetch=build_fetchxml_by_alias(context,table,id, type="delete")
            fetchparser=FetchXmlParser(fetch, context)
            rs=DatabaseServices.exec(fetchparser,context, fetch_mode=0)
            result={"rows_affected": rs.get_cursor().rowcount}
            rs.close()
            return result
        except RestApiNotAllowed as err:
            abort(400, f"{err}")
        except Exception as err:
            abort(500,f"{err}")

    @api.doc(parser=create_parser_put())
    def put(self,table,id):
        try:
            create_parser_put().parse_args()
            context=g.context

            if request.json==None:
                abort(400, "cannot extract json data in body %s %s" % (table,id))

            fetch=build_fetchxml_by_alias(context, table, id, request.json, type="update")
            fetchparser=FetchXmlParser(fetch, context)
            rs=DatabaseServices.exec(fetchparser,context, fetch_mode=0)
            result={"rows_affected": rs.get_cursor().rowcount}
            rs.close()
            return result
        except RestApiNotAllowed as err:
            abort(400, f"{err}")
        except Exception as err:
            abort(500,f"{err}")


    @api.doc(parser=create_parser_get())
    def get(self,table,id,field=""):
        try:
            create_parser_get().parse_args()
            context=g.context

            fetch=build_fetchxml_by_alias(context, table, id, type="select")
            fetchparser=FetchXmlParser(fetch, context)
            rs=DatabaseServices.exec(fetchparser,context, fetch_mode=1)
            if rs.get_result()==None:
                abort(400, "Item not found => %s" % id)

            if field=="":
                return rs.get_result()
            else:
                return rs.get_result()[field]

        except RestApiNotAllowed as err:
            abort(400, f"{err}")
        except Exception as err:
            abort(500,f"{err}")
Exemple #4
0
    def get(self, path="index.htm", session_id=None, content_name=None):
        try:
            logger.info(f"Path: {path}")
            logger.info(f"content_name: {content_name}")
            logger.info(f"session_id: {session_id}")

            create_parser().parse_args()
            context = g.context

            portal_id = "default"
            #
            # content class
            #
            if not path.endswith("login.htm"):
                pass

            #
            # render the defined jinja template (in case ofahtm file)
            #
            if path.endswith('.htm'):
                next = HTTPRequest.redirect(request)
                logger.info(f"Redirect : {next}")

                fetch = build_fetchxml_by_alias(context,
                                                "api_portal",
                                                portal_id,
                                                type="select")
                fetchparser = FetchXmlParser(fetch, context)
                rs = DatabaseServices.exec(fetchparser, context, fetch_mode=1)
                if rs.get_result() == None:
                    abort(404, "Portal not found => %s" % id)

                # render the content first
                if content_name == None:
                    content_name = HTTPRequest.get_querystring_value(
                        request, "content_name", default="home")

                content = self.__get_content(context, portal_id, content_name)
                if content == None:
                    abort(404, "Content not found => %s" % content_name)

                params = {
                    "context": context,
                    "content_name": content_name,
                    "content_id": content['id']
                }

                template = JinjaTemplate.create_string_template(
                    context,
                    content['content'].encode('utf-8').decode('utf-8'))
                content_str = template.render(params)

                #
                # Render the complete page
                #
                params['content'] = content_str
                template = JinjaTemplate.create_file_template(context, path)
                page_str = template.render(params)

                response = make_response(page_str)
                response.headers['content-type'] = 'text/html'

                return response
            else:
                www_root = FileSystemTools.format_path(
                    AppInfo.get_current_config('ui', 'wwwroot',
                                               exception=True))
                return send_file(f"{www_root}{path}")

        except ConfigNotValid as err:
            logger.exception(f"Config not valid {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)
        except jinja2.exceptions.TemplateNotFound as err:
            logger.exception(f"TemplateNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(
                    context, 404, f"Template not found {err}"), 404)
        except FileNotFoundError as err:
            logger.exception(f"FileNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 404,
                                                     f"File not found {err}"),
                404)
        except RestApiNotAllowed as err:
            logger.exception(f"RestApiNotAllowed Exception: {err}")
            return redirect(f"/ui/login?redirect=/{path}", code=302)
        except Exception as err:
            logger.exception(f"Exception: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)
Exemple #5
0
 def tearDown(self):
     AppInfo.save_context(self.context, True)
     AppInfo.logoff(self.context)
Exemple #6
0
 def setUp(self):
     AppInfo.init(__name__, CONFIG['default'])
     session_id=AppInfo.login("root","password")
     self.context=AppInfo.create_context(session_id)
Exemple #7
0
class PostFile(Resource):
    api = AppInfo.get_api()

    @api.doc(parser=create_parser())
    def get(self, path):
        try:
            context = g.context
            connection = context.get_connection()

            file = File()
            result = file.read_file(context, path)

            if result == None:
                return make_response(
                    {
                        "status": "Err",
                        "error": f"File not found: {path}"
                    }, 404)

            response = make_response(result['file'])
            response.headers.set('Content-Type', result['mime_type'])
            #response.headers.set('Content-Disposition', 'attachment', filename='test.jpg')
            response.headers.set('Content-Disposition',
                                 'inline',
                                 filename=result['name'])
            return response

        except Exception as err:
            logger.exception(f"Exception: {err}")
            return make_response({"status": "Err", "error": str(err)}, 500)

    @api.doc(parser=create_parser())
    def post(self, path):
        try:
            context = g.context
            connection = context.get_connection()
            result = []

            for f in request.files.getlist('file'):
                file = File()
                file.create_file(context, f, path)
                result.append({
                    "status": "OK",
                    "file_id": file.get_file_id(),
                    "remote_path": path
                })

            return make_response(dict({
                "results": result,
                "status": "ok"
            }), 200)

        except Exception as err:
            logger.exception(f"Exception: {err}")
            return make_response({"status": "Err", "error": str(err)}, 500)

    @api.doc(parser=create_parser())
    def put(self, path):
        try:
            context = g.context
            connection = context.get_connection()
            result = []
            for f in request.files.getlist('file'):
                file = File()
                file.update_file(context, f, path)
                result.append({
                    "status": "OK",
                    "file_id": file.get_file_id(),
                    "remote_path": path
                })

            return make_response(dict({
                "results": result,
                "status": "ok"
            }), 200)

        except FileNotFoundInDatabase as err:
            logger.exception(f"FileNotFoundInDatabase: {err}")
            return make_response({"status": "Err", "error": str(err)}, 404)
        except Exception as err:
            logger.exception(f"Exception: {err}")
            return make_response({"status": "Err", "error": str(err)}, 500)
Exemple #8
0
from core.appinfo import AppInfo
from core.meta import build_table_fields_meta
from config import CONFIG
from core.log import create_logger

logger=create_logger(__name__)

parser = argparse.ArgumentParser(description='Build the metadata cache.')
parser.add_argument('--user','-u', type=str, help='restapi user')
parser.add_argument('--password','-p', type=str, help='restapi password')
args = parser.parse_args()

user=args.user
password=args.password

AppInfo.init(__name__, CONFIG['default'])

print(f"Host............:{AppInfo.get_current_config('mysql','host')}")
print(f"Database........:{AppInfo.get_current_config('mysql','database')}")
print(f"User............:{AppInfo.get_current_config('mysql','user')}")

session_id=AppInfo.login(args.user,args.password)
if session_id==None:
    print(f"connot log in")
    sys.exit(-1)

print(f"Session.........:{session_id}")
context=AppInfo.create_context(session_id)

build_table_fields_meta(context)
Exemple #9
0
import xml.etree.ElementTree as ET

from core.database import CommandBuilderFactory as factory, DbConnection, FetchXmlParser
from config import CONFIG
from core.appinfo import AppInfo
from services.fetchxml import read_dataview_meta

AppInfo.init(__name__, CONFIG['default'])
connection=DbConnection(AppInfo.create_connection())

fetch="""
<restapi>
    <table name="api_user"/>
    <select>
        <field name="id;select id from log_logs;--"/>
        <field name="username"/>
    </select>
</restapi>
"""

fetch="""
<restxml>
<table name="api_user" alias="u"/>
<select>
    <field name="mode_create" table_alias="p"/>
    <field name="mode_read" table_alias="p"/>
    <field name="mode_update" table_alias="p"/>
    <field name="mode_delete" table_alias="p"/>
    <field name="is_admin" table_alias="u" alias="user_is_admin"/>
    <field name="username" table_alias="u"/>
    <field name="table_id" table_alias="p"/>