Harsh Jain Harsh Jain - 1 year ago 102
Python Question

What can I use to pass the file argument in the script from the html code to cherrypy function

So what can I do to pass the argument to the function.

import os, random, string
import cherrypy

class StringGenerator(object):

def index(self):
return """<!DOCTYPE html>

<html lang="en">


<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- The above 3 meta tags *must* come first in the head; any other head

content must come *after* these tags -->

<title>Bootstrap 101 Template</title>

<!-- Bootstrap -->

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"



<div class="jumbotron">

<p ><h4 class='text-success' style='margin-left:30%;'>This is the twitter
word select </h1></p>

<form class="form-inline" action="generate/" style='margin-left:20%;'
enctype= "multipart/form-data">

<div class="form-group" >

<label for="exampleInputName2">Enter the file name</label>

<input type="file" class="form-control" name="file1" id="file" placeholder=" enter the file ">

</div><div class="form-group" >

<label for="exampleInputName2">Enter the prefrence</label>

<input type="text" class="form-control" name="length" id="exampleInputName2" placeholder=" enter the preference ">


<button type="submit" class="btn btn-primary">Result</button>


</div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->

<script src="js/bootstrap.min.js"></script>



def generate(self, length,file1):
some_string = "harsh"+length
cherrypy.session['mystring'] = some_string
fp = open(file1)
return fb

def display(self):
return cherrypy.session['mystring']

if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())

'/static': {

'tools.staticdir.on': True,
'tools.staticdir.dir': './public'
cherrypy.quickstart(StringGenerator(), '/', conf)

Answer Source

Take a look into the file cherrypy files tutorial, but to provide you with a concrete answer, your generate method has to use the file attribute of the file1 parameter.

For example, this method would work:

def generate(self, length, file1):            
    some_string = "harsh" + length        
    cherrypy.session['mystring'] = some_string        
    file_content = file1.file.read()
    return file_content

You can also operate on the file attribute to get more information, it's an instance of a python TemporaryFile.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download