コード例 #1
0
def configureApp(path, app, properties):
    """After it has been created it is populated"""
    print "Configuring app: " + app


    #where to put template chains
    templates = os.path.join(path, 'templates')

    #generate themes
    theme = path + "/static/"
    print "Generating: " + theme
    try:
        call(["mkdir", theme])
        call(["mkdir", templates])
        if call(["cp","-a", os.path.join(consts.RESOURCES, 'themes', properties['theme'],'static','.'), theme]) == 1:
            if call(["cp", "-a", os.path.join(consts.PATH, properties['theme'], 'static',  '.'), theme]) == 1:
                print "Failed to find theme: " + properties['theme'] + " static files"
                sys.exit(1)
        if call(["cp", "-a", os.path.join(consts.RESOURCES, 'themes', properties['theme'], 'templates', '.'), templates]) == 1:
            if call(["cp", "-a", os.path.join(consts.PATH, properties['theme'], 'templates',  '.'), templates]) == 1:
                print "Failed to find theme " + properties['theme'] + " templates"

        call(["cp", "-a", os.path.join(consts.RESOURCES, 'themes', 'core', '.'), theme])
        call(["cp", "-a", os.path.join(consts.RESOURCES, 'templatechains', 'core','.'), templates])
    except:
        print "Failed to generate theme"
    
    #generate the models
    try:
        generateModels(path,app,properties['models'])

        #when done writing models for this app migrate it
        #call([consts.PYTHON, consts.MANAGE, "schemamigration", app, "--intial"])

        #generate default html for displaying the models, these are not fullon pages rather
        #they are small snipets that can be loaded by other pages by using a view to access them
        generateModelView(path,app,properties['models'])
        
        #generate middletier functions for each model
        generateMiddletier(path,app,properties['models'])
        
        #generate the form generators
        generateForms(path,app,properties['models'])
        
    except KeyError:
        #but we still want to make a models file
        writeFile(os.path.join(path,'models.py'), "from django.contrib.auth.models import User")
        print app + " has no models"

    if app == 'main':
        #set urls to callback to the middletier
        addURL('api/login/', 'main.middletier.login', 'login')
        addURL('api/logout/', 'main.middletier.logout', 'logout')
        addURL('api/signup/', 'main.middletier.signup', 'signup')

        #need to put in the context processor that allows us to access login/logout/signout stuff
        call(["cp", os.path.join(consts.RESOURCES,'processors','context_processors.py'),os.path.join(consts.PROJECT,'main','context_processors.py')])
        #copy in the middletier
        call(["cp", os.path.join(consts.RESOURCES,'middletier','middletier.py'),os.path.join(consts.PROJECT,'main','middletier.py')])
        #copy in the form data
        call(["cp", os.path.join(consts.RESOURCES,'userforms.html'),os.path.join(consts.PROJECT,'main','templates','userforms.html')])
コード例 #2
0
def generatePage(app, name, appPath, parent, properties, top):
    """
    Generate a page given a dict of properties
    
    A page consists of both a view and a template both are generated by this function.
    """

    print "Generating page: " + name

    #basics for each page template
    tabs = 0
    page = "<!-- Generated code for page: " + name + " -->\n" 
    page += tabify("{%% extends \"%s.html\" %%}" % parent, tabs)

    
    #Generate unique portion for each page
    try:
        page += tabify(("{%% block title %%}%s{%% endblock %%}" % properties["title"]), tabs)
    except KeyError:
        pass #no title for page


    #if this is a top level page fill in the content block
    if top:
        try:
            page += "{% block content %}" + handlePercentToken(properties["template"],'{{ ','|safe }}') + "{% endblock %}"
        except KeyError:
            print "Page " + name + " has no content"
    else:#otherwise we just pop everything in assuming the percent tokens are set up right
        try:
            page += handlePercentToken(properties["template"],'{{ ','|safe }}')
        except KeyError:
            print "page " + name + " has no content"

    with open(os.path.join(appPath, 'templates', name+'.html'), 'w') as f:
        f.write(page)
        
    tabs = 0
    #write view
    #urls need to count capture groups
    args = "request"

    try:
        counter = 1
        for symbol in properties["url"]:
            if symbol == "(": #assume matching for now
                args += ",u_" + str(counter)
                counter += 1
    except KeyError:
        pass #didnt have a url
    
    view = ""
    
    #now the definition of the view function
    view += tabify("def %s(%s):" % (name, args), tabs)
    tabs += 1

    #time to call the access function
    try:
        login = properties['access']['login'] #requires a login
    except KeyError:
        login = "******"

    try:
        groups = properties['access']['groups'] #get groups required
    except KeyError:
        groups = ""


    try:
        error_message = "messages.add_message(request, messages.ERROR, '%s')" % properties['access']['failmessage']
    except KeyError:
        error_message = "messages.add_message(request, messages.ERROR, 'Something went wrong man!')"

    try:
        redirect = "return %s(request)" % properties['access']['fail']
    except KeyError:
        redirect = "return HttpResponse('Denied', status=403)"

    view += tabify("if not permissionsCheck(request,%s,'%s'):" % (login,groups), tabs)
    tabs += 1
    view += tabify(error_message, tabs)
    view += tabify(redirect, tabs)
    tabs -= 1

    #time to define variables in the page
    view += tabify("d = {}",tabs) #to hold the variables
    for key in iter(properties):
        if key not in ["title", "url", "template", "pages", "access"]: #predefined keys, anything else is a variable
            view += decodePageKey(key,properties[key],tabs)

    view += tabify("return render(request,\"%s.html\",d)" % name, tabs)
    
    #write the view files
    writeFile(os.path.join(appPath, 'views.py'), view, 'a')

    
    #adds a url mapping
    try:
        addURL(properties['url'],"%s.views.%s" % (app, name), name)
    except KeyError:
        pass #wasnt a leaf page, dont really care if its missing a url

    #generate all sub pages
    try:
        for key in iter(properties['pages']):
            generatePage(app, key, appPath, name, properties['pages'][key], False)
    except KeyError:
        pass #this was a leaf page
コード例 #3
0
def generateMiddletierForModel(app, model, properties):
    """Generate portion of middletier file for a particular model"""
    result = "\n\n#interactions for model " + model + "\n"

    fields = properties['fields']
    unique = []
    required = []
    for field in iter(fields):
        if 'unique' in fields[field].keys():
            unique.append(field)
        if 'required' in fields[field].keys():
            required.append(field)


    #TODO verify that unique and required are being honored
    #TODO also this is a pretty horrible way to generate these functions, should implemenmt a template system (again) for it

    result += "from django.http import HttpResponse\n"

    #create function
    result += "def create%s(request):\n" % model
    result += "    if request.method == 'POST':\n"
    result += "        data = request.POST.copy()\n"
    result += "        del data['csrfmiddlewaretoken'] #remove this since it is not a part of the object\n"
    result += "        from %s.forms import %sForm\n" % (app,model)
    result += "        form = %sForm(data)\n" % model
    result += "        if form.is_valid():\n"
    result += "            data = form.cleaned_data\n"
    result += "            new%s = form.save()\n" % model
    result += "            new%s.save()\n" % model
#    result += "            newObject = %s(**data)\n" % model
#    result += "            newObject.save()\n"
    result += "            return HttpResponse('\\'Succesfully Created\\'')\n"
    result += "        return HttpResponse('\\'Data Unclean\\'')\n\n"
    addURL('api/%s/%s/create/'%(app,model),'%s.middletier.create%s'%(app,model),'create_%s' % (model))

    #retrieve function
    result += "def retrieve%s(request):\n" % model
    result += "    if request.method == 'POST':\n"
    result += "        data = request.POST\n"
    result += "        filters = data['filters']\n"
    result += "        qs = %s.objects.filter(**filters)\n" % model
    result += "        return HttpResponse(serializers.serialize([qs]))\n"
    result += "    return HttpResponse('Please send data as POST')\n\n"

    #delete function
    result += "def delete%s(request):\n" % model
    result += "    if request.method == 'POST':\n"
    result += "        data = request.POST\n"
    result += "        filters = data['filters']\n"
    result += "        qs = %s.objects.filter(**filters)\n" % model
    result += "        count = 0\n"
    result += "        for obj in qs:\n"
    result += "            obj.delete()\n"
    result += "            count += 1\n"
    result += "        return HttpResponse('Deleted %s objects' % count)\n"
    result += "    return HttpResponse('Please send data as POST')\n\n"

    #unsure how edit differs from creation/deletion must pontificate

    return result
コード例 #4
0
def generatePage(app, name, appPath, parent, properties, top):
    """
    Generate a page given a dict of properties
    
    A page consists of both a view and a template both are generated by this function.
    """

    print "Generating page: " + name

    #basics for each page template
    tabs = 0
    page = "<!-- Generated code for page: " + name + " -->\n"
    page += tabify("{%% extends \"%s.html\" %%}" % parent, tabs)

    #Generate unique portion for each page
    try:
        page += tabify(
            ("{%% block title %%}%s{%% endblock %%}" % properties["title"]),
            tabs)
    except KeyError:
        pass  #no title for page

    #if this is a top level page fill in the content block
    if top:
        try:
            page += "{% block content %}" + handlePercentToken(
                properties["template"], '{{ ', '|safe }}') + "{% endblock %}"
        except KeyError:
            print "Page " + name + " has no content"
    else:  #otherwise we just pop everything in assuming the percent tokens are set up right
        try:
            page += handlePercentToken(properties["template"], '{{ ',
                                       '|safe }}')
        except KeyError:
            print "page " + name + " has no content"

    with open(os.path.join(appPath, 'templates', name + '.html'), 'w') as f:
        f.write(page)

    tabs = 0
    #write view
    #urls need to count capture groups
    args = "request"

    try:
        counter = 1
        for symbol in properties["url"]:
            if symbol == "(":  #assume matching for now
                args += ",u_" + str(counter)
                counter += 1
    except KeyError:
        pass  #didnt have a url

    view = ""

    #now the definition of the view function
    view += tabify("def %s(%s):" % (name, args), tabs)
    tabs += 1

    #time to call the access function
    try:
        login = properties['access']['login']  #requires a login
    except KeyError:
        login = "******"

    try:
        groups = properties['access']['groups']  #get groups required
    except KeyError:
        groups = ""

    try:
        error_message = "messages.add_message(request, messages.ERROR, '%s')" % properties[
            'access']['failmessage']
    except KeyError:
        error_message = "messages.add_message(request, messages.ERROR, 'Something went wrong man!')"

    try:
        redirect = "return %s(request)" % properties['access']['fail']
    except KeyError:
        redirect = "return HttpResponse('Denied', status=403)"

    view += tabify(
        "if not permissionsCheck(request,%s,'%s'):" % (login, groups), tabs)
    tabs += 1
    view += tabify(error_message, tabs)
    view += tabify(redirect, tabs)
    tabs -= 1

    #time to define variables in the page
    view += tabify("d = {}", tabs)  #to hold the variables
    for key in iter(properties):
        if key not in ["title", "url", "template", "pages", "access"
                       ]:  #predefined keys, anything else is a variable
            view += decodePageKey(key, properties[key], tabs)

    view += tabify("return render(request,\"%s.html\",d)" % name, tabs)

    #write the view files
    writeFile(os.path.join(appPath, 'views.py'), view, 'a')

    #adds a url mapping
    try:
        addURL(properties['url'], "%s.views.%s" % (app, name), name)
    except KeyError:
        pass  #wasnt a leaf page, dont really care if its missing a url

    #generate all sub pages
    try:
        for key in iter(properties['pages']):
            generatePage(app, key, appPath, name, properties['pages'][key],
                         False)
    except KeyError:
        pass  #this was a leaf page