Django: Uploading an XML file from HTML page - python

I am using Django framework and python scripts for validating XML files.
I usually parse the XML file, which is already present in the defined location, using the below code.
import xml.etree.ElementTree as ET
tree = ET.parse('config.xml')
However, now I want to add the file dynamically from the front end browse file option and place it in the above ET.parse('file.xml') location. What is the best way to achieve this?

<form action="/handle_xml_upload/" enctype="multipart/form-data" method="post">
{% csrf_token %}
<input type="file" name="xmlfile">
<input type="submit" value="upload xml file">
</form>
and in views.py
def handle_xml_upload(request):
xmlfile = request.FILES['xmlfile']
tree = ET.parse(xmlfile)
# ...
of course, you need adjust your urls.py as well ;)

Related

Parse HTML string from a file and remove element using xpath and write it to same file in python

For my project, I have to remove selective content from a html file using python xpath.
The selective element can be removed using .remove() method, however the content in file looks same.
How do I write the modified content to that file again?
Though If i try to write the same tree object to file using open().write(etree.tostring(tree_obj)), will the content differs for unicode pages? Is there anyother way to keep the modified file?
Why the header tags in below output has different value after printing the tree object?
Please suggest.
Below is my code sample.
Example: I need to remove all div tags inside the html page.
HTML file:
<html>
<head>test</head>
<body>
<p>welcome to the world</p>
<div id="one">
<p>one</p>
<div id="one1">one1</div>
<ul>
<li>ones</li>
<li>twos</li>
<li>threes</li>
</ul>
</div>
<div id="hell">
<p>heaven</p>
<div id="one1">one1</div>
<ul>
<li>ones</li>
<li>twos</li>
<li>threes</li>
</ul>
</div>
<input type="text" placeholder="enter something.." />
<input type="button" value="click" />
</body>
</html>
Python file:
# _*_ coding:utf-8 _*_
import os
import sys
import traceback
import datetime
from lxml import etree, html
import shutil
def process():
fd=open("D:\\hello.html")
tree = html.fromstring(fd.read())
remove_tag = '//div'
for element in tree.xpath(remove_tag):
element.getparent().remove(element)
print etree.tostring(tree)
process()
OUTPUT:
<html>
<head/><body><p>test
</p>
<p>welcome to the world</p>
<input type="text" placeholder="enter something.."/>
<input type="button" value="click"/>
</body></html>
I haven't worked on python but i have played with parsing html based websites using Java with help of library jsoup.
Python also has similar one like this. Beautiful soup. You can play with this thing to get desired output.
Hope it helps.
Have you tried using python's standard library re?
import re</br>
re.sub('<.*?>','', '<nb>foobar<aon><mn>')
re.sub('</.*?>','', '</nb>foobar<aon><mn>')
The above two operations could be used in combination to remove all the html tags. It can be easily modified to remove the div tags too.

uploading html files and using python

For my forum, I tried uploading a file with html using:
<form action="profiles.py" method="post">
<label class="labelOne" for="pics">Change your Profile pic </label>
<input type="file" name="uploadField" />
My python function takes that file, creates a file under userprofiles, and writes the data to it:
file = open('../data/accounts/userprofiles/'+str(form['name'].value)+'/'+'profilepics', 'w+')
file.write(str(form.getvalue('uploadField')))
file.close()
So, If I want burger.jpg to be my picture, I upload it, python takes that and creates a file with that name burger.jpg using w+ and then it writes the data to it(which should be the image).
However for some reason, I get no image.
What should I try next?
Set the enctype of your form to multipart/form-data
<form action="profiles.py" method="post" enctype="multipart/form-data">

django - how to post array of images to views

i am stuck on this issue since yesterday. i have a form where user can select more image files and submit. now i am not able to catch those POSTED image files in my views.py.
my html:
<input type="file" name="images[]" />
<input type="file" name="images[]" />
and in my views.py i did this:
images = request.POST.getlist('images[]')
but once i print images, i am getting [], empty array. what am i doing wrong? i want to get all selected image files and save them into db in my view.
EDIT:
this is my html:
<form action="/save/" method="post" enctype="multipart/form-data">
<input type="file" name="images[]" />
<input type="file" name="images[]" />
<input type="submit" value="send" />
</form>
this is my views.py
fotos = request.POST.getlist('images[]')
for i in range(len(fotos)):
print fotos[i]
here it is printing [], and not the names of each images. why is this array empty?
thanks for help.
When Django handles a file upload, it's a little different than a regular POST field. The data is place in request.FILES and needs to be accessed there. The documentation about handling file uploads is a great starting point.

Sending data to server flask html

I am trying to create a simple checkbox that sends the data to server here is my html code.
<form action="." method="POST">
<div class="checksheet">
<input id="XML Parser" class="checkbox" type="checkbox"/>XML Parser
<input id="Feed Parser" class="checkbox" type="checkbox"/>Feed Parser
<input id="Text Parser" class="checkbox" type="checkbox"/>Text Parser
<input id="Case Normalization" class="checkbox" type="checkbox"/>Case Normalization
<input id="Stemmer" class="checkbox" type="checkbox"/> Stemmer
</div>
<div class="submit"><input type="submit" value="Send" name="raw_text"></div>
</form>
What I am trying to do is very similar to the question asked here: Send Data from a textbox into Flask?
But except with the text box.. I have checkboxes.
But I get this error:
Not Found
The requested URL was not found on the server.
If you entered the URL manually please check your spelling and try again.
MY server side code (in flask) is:
#app.route('/raw_text.html')
def home ():
file = "sample.xml"
contents = open(file).read()
contents = contents.decode('utf-8')
return render_template('raw_text.html', contents=contents,file=file)
#app.route('/raw_text.html',methods=['POST'])
def get_data():
print "REQUEST ",request.form()
data = request.form['raw_text']
print data
return "Processed"
Any suggestions.
Thanks
A few things:
Your checkbox elements need a name attribute, this is what is used when the data is sent to the back end. Each checkbox that is related to each other needs to have the same name.
Your action attribute needs to point to a URL. If you are posting it to the same page as the form, you can remove the attribute.
ID's cannot contain spaces.
To be accessible the check boxes need <label>s,

Creating an object with an external form

I have a upload form that is going to S3 --
<form action="https://test.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="id_file" />
<input type="submit" value="Upload to Amazon S3" name="upload">
</form>
When the form is submitted to S3, I also need to create an object in my db and get the id of the object. How would I do this (without redirecting to my view)? Thank you.
You could use an iframe to send the form and js to search for the id you are looking for in the retrieved page.
You could also use another script to perform the post method like php with the curl library. You could grab all the data retrieved from there, search for what you are looking for and add what you need to your database.

Categories