def create_file():
    """ Create files handler """
    if request.vars and not request.vars.token == session.token:
        redirect(URL('logout'))
    try:
        anchor = '#' + request.vars.id if request.vars.id else ''
        if request.vars.app:
            app = get_app(request.vars.app)
            path = abspath(request.vars.location)
        else:
            if request.vars.dir:
            	request.vars.location += request.vars.dir + '/'
            app = get_app(name=request.vars.location.split('/')[0])
            path = apath(request.vars.location, r=request)
        filename = re.sub('[^\w./-]+', '_', request.vars.filename)
        if path[-7:] == '/rules/':
            # Handle plural rules files
            if len(filename) == 0:
                raise SyntaxError
            if not filename[-3:] == '.py':
                filename += '.py'
            lang = re.match('^plural_rules-(.*)\.py$', filename).group(1)
            langinfo = read_possible_languages(apath(app, r=request))[lang]
            text = dedent("""
                   #!/usr/bin/env python
                   # -*- coding: utf8 -*-
                   # Plural-Forms for %(lang)s (%(langname)s)

                   nplurals=2  # for example, English language has 2 forms:
                               # 1 singular and 1 plural

                   # Determine plural_id for number *n* as sequence of positive
                   # integers: 0,1,...
                   # NOTE! For singular form ALWAYS return plural_id = 0
                   get_plural_id = lambda n: int(n != 1)

                   # Construct and return plural form of *word* using
                   # *plural_id* (which ALWAYS>0). This function will be executed
                   # for words (or phrases) not found in plural_dict dictionary.
                   # By default this function simply returns word in singular:
                   construct_plural_form = lambda word, plural_id: word
                   """)[1:] % dict(lang=langinfo[0], langname=langinfo[1])

        elif path[-11:] == '/languages/':
            # Handle language files
            if len(filename) == 0:
                raise SyntaxError
            if not filename[-3:] == '.py':
                filename += '.py'
            path = os.path.join(apath(app, r=request), 'languages', filename)
            if not os.path.exists(path):
                safe_write(path, '')
            # create language xx[-yy].py file:
            findT(apath(app, r=request), filename[:-3])
            session.flash = T('language file "%(filename)s" created/updated',
                              dict(filename=filename))
            redirect(request.vars.sender + anchor)

        elif path[-8:] == '/models/':
            # Handle python models
            if not filename[-3:] == '.py':
                filename += '.py'

            if len(filename) == 3:
                raise SyntaxError

            text = '# coding: utf8\n'

        elif path[-13:] == '/controllers/':
            # Handle python controllers
            if not filename[-3:] == '.py':
                filename += '.py'

            if len(filename) == 3:
                raise SyntaxError

            text = '# coding: utf8\n# %s\ndef index(): return dict(message="hello from %s")'
            text = text % (T('try something like'), filename)

        elif path[-7:] == '/views/':
            if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin):
                filename = 'plugin_%s/%s' % (request.vars.plugin, filename)
            # Handle template (html) views
            if filename.find('.') < 0:
                filename += '.html'
            extension = filename.split('.')[-1].lower()

            if len(filename) == 5:
                raise SyntaxError

            msg = T(
                'This is the %(filename)s template', dict(filename=filename))
            if extension == 'html':
                text = dedent("""
                   {{extend 'layout.html'}}
                   <h1>%s</h1>
                   {{=BEAUTIFY(response._vars)}}""" % msg)[1:]
            else:
                generic = os.path.join(path, 'generic.' + extension)
                if os.path.exists(generic):
                    text = read_file(generic)
                else:
                    text = ''

        elif path[-9:] == '/modules/':
            if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin):
                filename = 'plugin_%s/%s' % (request.vars.plugin, filename)
            # Handle python module files
            if not filename[-3:] == '.py':
                filename += '.py'

            if len(filename) == 3:
                raise SyntaxError

            text = dedent("""
                   #!/usr/bin/env python
                   # coding: utf8
                   from gluon import *\n""")[1:]

        elif (path[-8:] == '/static/') or (path[-9:] == '/private/'):
            if (request.vars.plugin and 
                not filename.startswith('plugin_%s/' % request.vars.plugin)):
                filename = 'plugin_%s/%s' % (request.vars.plugin, filename)
            text = ''

        else:
            redirect(request.vars.sender + anchor)

        full_filename = os.path.join(path, filename)
        dirpath = os.path.dirname(full_filename)

        if not os.path.exists(dirpath):
            os.makedirs(dirpath)

        if os.path.exists(full_filename):
            raise SyntaxError

        safe_write(full_filename, text)
        log_progress(app, 'CREATE', filename)
        if request.vars.dir:
            result = T('file "%(filename)s" created',
                          dict(filename=full_filename[len(path):]))
        else:
            session.flash = T('file "%(filename)s" created',
                          dict(filename=full_filename[len(path):]))
        vars = {}
        if request.vars.id:
            vars['id'] = request.vars.id
        if request.vars.app:
            vars['app'] = request.vars.app
        redirect(URL('edit',
                 args=[os.path.join(request.vars.location, filename)], vars=vars))

    except Exception, e:
        if not isinstance(e, HTTP):
            session.flash = T('cannot create file')

    if request.vars.dir:
        response.flash = result
        response.headers['web2py-component-content'] = 'append'
        response.headers['web2py-component-command'] = """
            $.web2py.invalidate('#files_menu');
            load_file('%s');
            $.web2py.enableElement($('#form form').find($.web2py.formInputClickSelector));
        """ % URL('edit', args=[app,request.vars.dir,filename])
        return ''
    else:
    	redirect(request.vars.sender + anchor)
dataset/ETHPy150Open uwdata/termite-data-server/web2py/applications-original/admin/controllers/default.py/create_file/original