Code Monkey home page Code Monkey logo

argparseweb's Introduction

Version Status

README

This web.py based simple module allows you to automatically set up a simple HTTP web server out of advanced argparse.ArgumentParser objects and similar (argh.ArgumentParser) ones. Using this on top of argh lets you automatically generate web user interface out of simple functions defined in your application. This package was made for getting your personal command line scripts to the next stage - internal shared utilities.

How do I set up?

For a production like setup you'll need:

  1. make your main script expose an application global object by calling webui.Webui.wsgi() method

  2. modify index.wsgi to fit your application (trivial configuration, import aforementioned application)

  3. set up a wsgi supporting apache (or any other) server

For debugging like setup you'll need (but since it's used for internal tools, this might also be fine):

  1. replace methods like argparse.ArgumentParser.parse_args() or argh.dispatch() with webui.Webui.getone() or webui.Webui.dispatch() respectively.

dispatch() will instantiate a web service and call dispatch methods (either provided by the user - you - or dispatch methods of supporting argument parsers like argh)

get() and getone() wrap the dispatch() method and yield results as they are submitted in the web form, providing an interface that resembles the parse_args() method.

Dependencies

argparseweb requires web.py to be available. You can install it (check for the latest version) with: pip install web.py

Basic examples

This example will set up an http server, get one valid input, tear the http server down, print a welcoming message to stdout and exit:

import argparse
from argparseweb import *

def main():
  parser = argparse.ArgumentParser()

  parser.add_argument("name", default="Anonymous")

  # previously opts = parser.parse_args()
  opts = webui.Webui(parser).getone()
  print("Hello {name},\nthis is a simple example.".format(name=opts.name))

if __name__ == "__main__":
  main()

This example will also run until stopped, printing a welcoming message for every valid input:

import argparse
from argparseweb import *

def main():
  parser = argparse.ArgumentParser()

  parser.add_argument("name", default="Anonymous")

  # previously opts = parser.parse_args()
  for opts in webui.Webui(parser).get():
    print("Hello {name},\nthis is a simple example.".format(name=opts.name))

if __name__ == "__main__":
  main()

This example will print the welcoming message in the http response, sending it back to the user:

import argparse
from argparseweb import *

def welcome(opts):
  print("Hello {name},\nthis is a simple example.".format(name=opts.name))

def main():
  parser = argparse.ArgumentParser()

  parser.add_argument("name", default="Anonymous")

  # previously opts = parser.parse_args()
  webui.Webui(parser).dispatch(welcome, parsed=True)

if __name__ == "__main__":
  main()

A more complicated example

This snippet includes three modes of operation for the webui utility:

  1. first and simplest: dispatch methods using argh's automatic function to command line parser facilities, this is completely unrelated to webui and that way you won't lose existing command line usage ability.

  2. getting --webui as the first command line argument, sets up a development web server (defaults to *:8080) and is ready to use.

  3. exposing an application global object that supports the wsgi interface. once you point a browser with correct wsgi configuration (was a bit of a pain for me first time) it'll work like magic :)

myapp.py:

import argparse
from argparseweb import *

def get_parser():
  """Generate generic argument parser"""
  cmd_parser = argh.ArghParser()
  cmd_parser.add_commands([...])

  return cmd_parser

def main_1():
  # k. get the parser as usual
  cmd_parser = get_parser()

  # last chance to use webui, if --webui is passed as first command line argument
  # remove it as let webui handle the rest
  if sys.argv[1] == '--webui':
    sys.argv.remove('--webui')
    webui.Webui(cmd_parser).dispatch() # second mode of operation - development/fast setup
  else:
    # dispatch either webui or argh
    cmd_parser.dispatch() # first mode of operation - regular command line

def main_2():
  parser = argparse.ArgumentParser()

  # TODO: fill argparse

  # opts = parser.parse_args()
  opts = webui.Webui(parser).getone()

  # TODO: use opts as you would with any ArgumentParser generated namespace,
  # opts is really a namespace object directly created by parser, and webui only compiled an argument sequence
  # based on the filled form, passed into parser.parse_args() and back to you

def wsgi():
  global application

  # create a webui application using the command line argument parser object
  # and make it's wsgi function the global `application` parameter as required by wsgi
  cmd_parser = get_parser()
  application = webui.Webui(cmd_parser).wsgi() # third mode of operation - production wsgi application

if __name__ == "__main__":
  # script initialized as main, lets do our trick
  main()
else:
  # if script wasn't initialized as main script, we're probably running
  # in wsgi mode
  wsgi()

index.wsgi:

# TODO: replace with your application path
# i found now way to get it automatically in wsgi :/
APP_DIR = '/var/www/myapp'

import sys, os
sys.path.insert(0, APP_DIR)
os.chdir(APP_DIR)

from myapp import application

More examples are at test.py

known issues

  • right now vary-length arguments (nargs='?', nargs='*', nargs='+') are limited to one argument because i didn't write the HTML required for that. i'm considering multiple text inputs or textarea with line separation, input (and code) are most welcome.

Done:

  • some code reordering is needed (split template to another file - it's grown quite big, handle action parameters better - shouldn't pass everything as html attributes although it's comfortable)
  • smoother integration into existing code.

argparseweb's People

Contributors

nirizr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

argparseweb's Issues

Including "%s" in argparse help text triggers help string replacement

When including %s in the help string for an argparse option, the string is being reformatted.
Example:

parser.add_argument("-loglevel",help="%s Logging level: None, Error, Warning, Info, Verbose, Debug or Progress [Info]",nargs=1,type=str)

actually results in the help text:

{'const': None, 'help': '%s Logging level: None, Error, Warning, Info, Verbose, Debug or Progress [Info]', 'option_strings': ['-loglevel'], 'dest': 'loglevel', 'required': False, 'nargs': 1, 'choices': None, 'default': None, 'container': <argparse._ArgumentGroup object at 0x1fac47cdaf865f>, 'type': <type 'str'>, 'metavar': None} Logging level: None, Error, Warning, Info, Verbose, Debug or Progress [Info]

Specifying dependencies (e.g. web)

It is probably desirable to specify the requirements / dependencies this project is build upon. When trying to install through pip install argparseweb people are likely being greeted by this message:
ImportError: No module named web

I am assuming web is this module here: https://pypi.python.org/pypi/web (pypi lists version 0.6.0, but it appears this was last released in 2009 as version 0.5.3 (http://pythonweb.org). That same website also discourages people actually using web and instead to use what is now called pyramid.

Templates directory is not installed as part of `setup.py`

When installing argparseweb (e.g. through pip install argparseweb) and then using it with import argparse the following error is shown:

IOError: [Errno 2] No such file or directory: '../lib/python2.7/site-packages/argparseweb/templates/input.html'

Which appears to be called from: https://github.com/nirizr/argparseweb/blob/master/argparseweb/page.py#L20

_form_template = web.template.frender(os.path.join(os.path.dirname(__file__), "templates/input.html"), globals={'type': type, 'basestring': basestring})

The reason is most likely a missing templates/input.html file, which has not been installed as part of setup.py.

No module named 'page' - Migrating from the deprecated web.py framework

Hey there,
I first installed web.py using pip install web.py, then installed this repo using pip install argparseweb.
Getting the following error during argparseweb install:

Collecting argparseweb
  Using cached argparseweb-0.1.2.tar.gz (8.8 kB)
    ERROR: Command errored out with exit status 1:
     command: /Users/saadbazaz/.virtualenvs/deepdub1/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/s9/k339_45j0ygg3zls9jn91xqm0000gn/T/pip-install-enl7cjw8/argparseweb_dd594d92584743acb991194d8e03e2c9/setup.py'"'"'; __file__='"'"'/private/var/folders/s9/k339_45j0ygg3zls9jn91xqm0000gn/T/pip-install-enl7cjw8/argparseweb_dd594d92584743acb991194d8e03e2c9/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/s9/k339_45j0ygg3zls9jn91xqm0000gn/T/pip-pip-egg-info-et5r22bn
         cwd: /private/var/folders/s9/k339_45j0ygg3zls9jn91xqm0000gn/T/pip-install-enl7cjw8/argparseweb_dd594d92584743acb991194d8e03e2c9/
    Complete output (9 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/s9/k339_45j0ygg3zls9jn91xqm0000gn/T/pip-install-enl7cjw8/argparseweb_dd594d92584743acb991194d8e03e2c9/setup.py", line 3, in <module>
        import argparseweb
      File "/private/var/folders/s9/k339_45j0ygg3zls9jn91xqm0000gn/T/pip-install-enl7cjw8/argparseweb_dd594d92584743acb991194d8e03e2c9/argparseweb/__init__.py", line 2, in <module>
        from .webui import *
      File "/private/var/folders/s9/k339_45j0ygg3zls9jn91xqm0000gn/T/pip-install-enl7cjw8/argparseweb_dd594d92584743acb991194d8e03e2c9/argparseweb/webui.py", line 3, in <module>
        import page
    ModuleNotFoundError: No module named 'page'
    ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/ec/0a/cb8d85a0b3e9829f9c444f17cd4aea673c2b1e980e5a7f3e5e98eb5885aa/argparseweb-0.1.2.tar.gz#sha256=06b5775e77797d8468a5c9a0e2c5b6aa2ed534f391818b705aae1ef148244b48 (from https://pypi.org/simple/argparseweb/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement argparseweb (from versions: 0.1.2)

I ruled out that there's an error in finding the module "page", which is dependent on web.py. And from what I read on the Internet, web.py is deprecated.

Are there any plans to update this repo? I have some ideas in mind, maybe they could help out.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.