Skip to content

Instantly share code, notes, and snippets.

@stevommmm
Last active August 29, 2015 14:06
Show Gist options
  • Save stevommmm/3caa3d2bb8952108b973 to your computer and use it in GitHub Desktop.
Save stevommmm/3caa3d2bb8952108b973 to your computer and use it in GitHub Desktop.
funcs to forms in python
import logging
import types
funcs = []
def decorator(func, *args, **kwargs):
if type(func) != types.FunctionType:
return decorator
funcs.append(func)
return func
def get_function_doc(func):
return func.__doc__
def get_function_args(func):
args = func.func_code.co_varnames
defs = func.func_defaults
defs_len = len(defs) * -1 # negate the number of kw variables so we zip from the end ( where kwargs should be you tosser )
func_vars = list(args[:defs_len])
func_vars.extend(zip(args[defs_len:], defs))
return func_vars
def decide_type(func_vars):
for x in func_vars:
if type(x) == types.StringType:
yield '<input type="text" name="{0}">'.format(x)
elif type(x) == types.TupleType:
if type(x[1]) == types.StringType:
yield '<input type="text" name="{0}" placeholder="{1}">'.format(*x)
elif type(x[1]) == types.IntType:
yield '<input type="number" name="{0}" placeholder="{1}">'.format(*x)
elif type(x[1]) == types.BooleanType:
yield '<input type="checkbox" name="{0}">'.format(*x)
else:
logging.debug('Unknown type %s, defaulting to text input', type(x[1]).__name__)
else:
raise ValueError('Unknown function arg type, where did you get this?')
@decorator
def test(hostname, username="root", tes=4):
print "test"
@decorator
def test2(hostname, rrrr=True, rrrrrr="test"):
print "test"
if __name__ == '__main__':
for f in funcs:
print list(decide_type(get_function_args(f)))
print get_function_doc(f)

Returned output

['<input type="text" name="hostname">', '<input type="text" name="username" placeholder="root">', '<input type="number" name="tes" placeholder="4">']
None
['<input type="text" name="hostname">', '<input type="checkbox" name="rrrr">', '<input type="text" name="rrrrrr" placeholder="test">']
None

With some quick formatting it can produce the following output

 <form>
	<p>None</p>
	<input type="text" name="hostname">
	<input type="text" name="username" placeholder="root">
	<input type="number" name="tes" placeholder="4">
</form>

<form>
	<p>None</p>
	<input type="text" name="hostname">
	<input type="checkbox" name="rrrr">
	<input type="text" name="rrrrrr" placeholder="test">
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment