Saving a data into a .txt file in django - python

I am working on a project in Django where I simply count the number of words when I input a sentence. I also try to save the number of words in a .txt file evry time I use the website.
The views.py is:
from django.http import HttpResponse
from django.shortcuts import render
def homepage(request):
return render(request,'home.html')
def count(request):
fulltext = request.GET['fulltext']
wordlist = fulltext.split()
f=open('abc.txt','a+')
f.write('\n')
f.write(wordlist)
f.close()
return render(request,'count.html', {'fulltext':fulltext, 'count':len(wordlist)})
The homepage where I give the input sentence is:
<h1> Word Count </h1>
<form action = "{% url 'count' %}">
<textarea col='40' rows = '5' name = "fulltext"></textarea>
<br/>
<input type = 'submit' value= 'count!' />
</form>
The page where I show the output along with the number of words is:
<h1> hey, there are {{count}} words</h1>
<h1> your text </h1>
{{fulltext}}
The program runs well in the UI portion. As I give the input sentence in the homepage and submit it, I get the results in the output page. It also generates a abc.txt file in the working directory. However, there is a repetation of the part of the code there as in the .txt file I get the same output twice. That is, if the input sentence is "Tom and Jerry" then the .txt file stores 3 (the number of words in the sentence) twice instead of once.
Can someone help?

Related

Python Jinja2 Render HTML template in certain style from strings

I am new to using Jinja2 and am trying to render an html file from several strings and lists.
Lets say I have a File path, a term, and a sentence.
Using these I want to create an html file which has the file path as well as the two sentences where the the word is bolded if it matches the term.
I.e.
file_path is "/usr/bin/local/cheese.txt"
term is "cheese"
sentence is "i am cheese cheese i am"
I want to create and html file that looks like this
<html>
<body>
<h2>Search results for <b>cheese</b> in the file</h2>
<p>/usr/bin/local/cheese.txt<br>
I am <b>cheese</b> <b>cheese</b> I am<br><br>
</body>
</html>
I have been trying to use Jinja2 but am having trouble creating an HTML file by specifying the formatting.
Here is what I have so far:
import jinja2
from jinja2 import Environment, FileSystemLoader
def render_template(template_filename, context):
return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
file_path = "/usr/bin/local/cheese.txt"
term = "cheese"
sentence = "i am cheese cheese i am"
context = {
'h2': "Search results for <b>" + terms + "</b>",
'urls': file_path, # for making the file path tag - not sure if right
'bold': term, # Do not think this is correct
'paragraph': sentence ## Do not think this is correct at all.
}
output = template.render_template("temp.html", context)
I do not think this is correct, but if someone who knows Jinja2 please tell me how to format this correctly I would be most grateful.
Please let me know if you need any more information.
Thank you for your time.
That's an example of your code in jinja2:
Python:
from jinja2 import Template
def render_template(template_filename, context):
with open(template_filename) as file_:
template = Template(file_.read())
return template.render(context)
file_path = "/usr/bin/local/cheese.txt"
term = "cheese"
sentence = "i am cheese cheese i am"
if term in sentence:
sentence = sentence.replace(term, '<b>%s</b>' % term)
context = {
'h2': "Search results for <b>" + term + "</b>",
'urls': file_path,
'bold': term,
'paragraph': sentence
}
output = render_template(your_template, context)
print(output)
Your template:
<html>
<body>
<h2>{{ h2|safe }}</h2>
<p>{{ urls }}}}<br>
{{ paragraph|safe }}<br><br>
</body>
</html>

Take list elements as strings in new lines on html page using python script

I have one list of bugs = ['bug1','bug2']. I want to put that in HTML page which I create from python script.
bgs = "print '\\n'.join(bugs_list)"
html_str = """
<html>
<body>
%(bugs_list)s
</body>
</html>
"""% {'bugs_list' : bgs}
How can I take bgs value as strings in new lines on html page?
bug1
bug2
bgs = exec(bgs) -> I can't take output of exec in variable, so got stuck here. Can someone please suggest me how to do this?

Retrieving HTML form data and storing in csv with Flask & Python

I have a small .py program, rendering 2 HTML pages. One of those HTML pages has a form in it. A basic form requesting a name, and a comment. I can not figure out how to take the name and the comment from the form and store it into the csv file. I have got the coding so that the very little I already manually input into the csv file is printed/returned on the HTML page, which is one of the goals. But I can't get the data I input into the form into the csv file, then back n the HTML page. I feel like this is a simple fix, but the Flask book makes absolutely no sense to me, I'm dyslexic and I find it impossible to make sense of the examples and the written explanations.
This is the code I have for reading the csv back onto the page;
#app.route('/guestbook')
def guestbook():
with open('nameList.csv','r') as inFile:
reader=csv.reader(inFile)
names=[row for row in reader]
return render_template('guestbook.html',names=names[1:])
And this is my form coding;
<h3 class="tab">Feel free to enter your comments below</h3>
<br />
<br />
<form action="" method="get" enctype="text/plain" name="Comments Form">
<input id="namebox" type="text" maxlength="45" size="32" placeholder="Name"
class="tab"/>
<br />
<textarea id="txt1" class="textbox tab" rows="6" placeholder="Your comment"
class="tab" cols="28"></textarea>
<br />
<button class="menuitem tab" onclick="clearComment()" class="tab">Clear
comment</button>
<button class="menuitem" onclick="saveComment()" class="tab">Save comment</button>
<br>
</div>
By what I understand all you need is to save the data into the file and you don't know how to handle this in Flask, I'll try to explain it with code as clear as possible:
# request is a part of Flask's HTTP requests
from flask import request
import csv
# methods is an array that's used in Flask which requests' methods are
# allowed to be performed in this route.
#app.route('/save-comment', methods=['POST'])
def save_comment():
# This is to make sure the HTTP method is POST and not any other
if request.method == 'POST':
# request.form is a dictionary that contains the form sent through
# the HTTP request. This work by getting the name="xxx" attribute of
# the html form field. So, if you want to get the name, your input
# should be something like this: <input type="text" name="name" />.
name = request.form['name']
comment = request.form['comment']
# This array is the fields your csv file has and in the following code
# you'll see how it will be used. Change it to your actual csv's fields.
fieldnames = ['name', 'comment']
# We repeat the same step as the reading, but with "w" to indicate
# the file is going to be written.
with open('nameList.csv','w') as inFile:
# DictWriter will help you write the file easily by treating the
# csv as a python's class and will allow you to work with
# dictionaries instead of having to add the csv manually.
writer = csv.DictWriter(inFile, fieldnames=fieldnames)
# writerow() will write a row in your csv file
writer.writerow({'name': name, 'comment': comment})
# And you return a text or a template, but if you don't return anything
# this code will never work.
return 'Thanks for your input!'

how do i print outputs to html page using python?

I want user to enter a sentence then I break up that sentence into a list. I got the html page down but i have trouble passing that sentence to python.
How do I properly send the user input to be processed by python and output it to a new page?
There are many Python web frameworks. For example, to break up a sentence using bottle:
break-sentence.py:
#!/usr/bin/env python
from bottle import request, route, run, view
#route('/', method=['GET', 'POST'])
#view('form_template')
def index():
return dict(parts=request.forms.sentence.split(), # split on whitespace
show_form=request.method=='GET') # show form for get requests
run(host='localhost', port=8080)
And the template file form_template.tpl that is used both to show the form and the sentence parts after processing in Python (see index() function above):
<!DOCTYPE html>
<title>Break up sentence</title>
%if show_form:
<form action="/" method="post">
<label for="sentence">Input a sentence to break up</label>
<input type="text" name="sentence" />
</form>
%else:
Sentence parts:<ol>
%for part in parts:
<li> {{ part }}
%end
</ol>
%end
request.forms.sentence is used in Python to access user input from <input name="sentence"/> field.
To try it you could just download bottle.py and run:
$ python break-sentence.py
Bottle server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
Now you can visit http://localhost:8080/.
Have you tried Google? This page sums up the possibilities, and is one of the first results when googling 'python html'.
As far as I know, the two easiest options for your problem are the following.
1) CGI scripting. You write a python script and configure it as a CGI-script (in case of most HTTP-servers by putting it in the cgi-bin/ folder). Next, you point to this file as the action-attribute of the form-tag in your HTML-file. The python-script will have access to all post-variables (and more), thus being able to process the input and write it as a HTML-file. Have a look at this page for a more extensive description. Googling for tutorials will give you easier step-by-step guides, such as this one.
2) Use Django. This is rather suited for larger projects, but giving it a try on this level may provide you certain insights, and wetting your appetite for future work ;)

Display files on HTML page as it is

I am using webpy framework for my project. I want to pass a file from my webpy program and display it on html page as it is(files may be any text files/program files). I passed a text file using following function from my webpy program.
class display_files:
def GET(self):
wp=web.input()
file_name=wp.name
repo_name=wp.repo
repo_path=os.path.join('repos',repo_name)
file_path=os.path.join(repo_path,file_name)
fp=open(file_path,'rU') #reading file from file path
text=fp.read() #no problem found till this line.
fp.close()
return render.file_display(text) #calling file_display.html
When I tried to display the file (here it is 'text') from 'file_display.html', it displays continuously without recognising newline.Here is my html file.
$def with(content)
<html>
<head>
<meta http-equiv="Content-Type" content="text/string;charset=utf-8" >
<title>File content</title>
</head>
<body>
<form name="file_content" id="file_content" methode="GET">
<p> $content</p>
</form>
</body>
<html>
How can I display file as it is in html page.
HTML treats amount of whitespace characters as a single whitespace. If the file that you are displaying contains this text:
line one
line two with indent
the rendered file_display.html will contain this HTML:
<p> line one
line two with indent</p>
Still, the newline and two spaces will be treated as a single space, and in browser it will look like this:
line one line two with indent
The pre element tells the browser that the text inside it is preformatted, so newlines and spaces should be kept. Thus, your template should look like:
<form name="file_content" id="file_content" methode="GET">
<pre>$content</pre>
</form>
As for Joseph's advice, web.py templating system will handle escaping for you. If your file contains characters like < or >, they will be replaced with < and >.
looks like you may need to globally replace any < or > with < or > respectively:
http://jsfiddle.net/BaULp/

Categories

Resources