Im building a project secure file sharing.which encrypts a file before uploading into local computer and decrypts while downloading if the user has the decryption key.I was stuck how to encrypt a file before uploading into my pc
I'm following this approach which is mentioned below.
https://ruddra.com/documentation-of-django-encrypt-file/#basic-usage
but i dont't know how to link with my code. can anyone help me
views.py
def upload(request):
context={}
if request.method == 'POST':
upload_file= request.FILES["document"]
fs=FileSystemStorage()
name=fs.save(upload_file.name, upload_file)
context['url'] = fs.url(name)
return render(request, 'accounts/upload.html',context)
upload.html
{% include 'accounts/main.html'%}
<pre>
Upload your files for sharing
</pre>
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="document">
<button type="submit">Upload</button>
</form>
{% if url %}
<p> Uploaded file:{{ url }}</p>
{% endif %}
{% endblock %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL= '/media/'
To encrypt a file BEFORE uploading to the server, it means you need to encrypt it within the browser - e.g. using JavaScript. Here's a thread that can help you to encrypt stuff in JS:
JavaScript AES encryption and decryption (Advanced Encryption Standard)
If you're feeling up to the challenge, look into running AES in WASM to speed up encryption (important for large files).
Note that in Django, all python code is executed ON THE SERVER. The linked example in the question shows how to encrypt files on the server AFTER uploading them:
https://ruddra.com/documentation-of-django-encrypt-file/#basic-usage
Note that encrypting the file on the browser before uploading is only a small portion of the whole problem. To have a secure file sharing service, you would probably want to have a way to share the key with the other users who need to decrypt it. For that you'd probably need to use asymmetric encryption, e.g., wrap (encrypt) the key using other users' public keys before uploading it.
Related
I'm a beginner and i'm making a blog with flask and html right now but it only can post title and content, but i want to post some picture init, so if anyone know whats the essayist way to post it (print the pic on flask app) and can storage in db file, can u please help me out? Because i'm stuck in this for so long.
If you are using a flask form to upload a file, then from flask_wtf.file import FileField can be used as the form field to upload files.
class UploadImageForm(Form):
file = FileField(label='File Upload')
submit = SubmitField('Submit')
On the HTML side you will want:
<form action="{{ url_for(your.route, **kwargs) }}" method="POST" enctype = "multipart/form-data">
{{ form.name_of_file_field }}
{{ form.submit }} <!-- Or an input tag -->
</form>
Then your route that will be called when the form is submitted must require a POST method. In development, you can store your files locally within the static folder, but I would advise to store them in remote storage before putting the app on a server.
Once the file is stored and uploaded, then in your html you can render the image with:
<img class="image" src="{{ url_for('static', filename=image_file_path) }}"> where image_file_path is the path to the image. This path should be stored as an environment variable. The image file name can be stored on your db within one of your models data columns as a string. I suggest creating UUID's as the image file name so you are not dependent on the user's upload (i.e. if the filename is in a different language).
Miguel Grinberg has a great tutorial on this that will cover all of this and more including working with image objects, image validation, and security: https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask
I've just started out with Django and have tried making an audio player application website. I (admin) want to be able to upload audio files that visitors can listen to.
I've created a model for succesfully uploading a file, taking a input file name, and storing it in a media folder in within my app directory:
class Song(models.Model):
name = models.CharField(max_length=125)
audio_file = models.FileField(upload_to='audio_player/media/audio_player/')
def __str__(self):
return self.name
In my Template I then have a for loop set up to create list of audio players for every different audio track.:
<div class="container">
{% for song in songs %}
<audio controls id="player">
<source src="{{ song.audio_file.url }}" type="audio/wav">
</audio>
{% endfor %}
</div>
Now this is where I've gotten stuck. The audio player appears accordingly, but you cannot play any audio. I've tried to check via Chromes DevTools and there the source, or src, is the correct file path to the files.
<source src="audio_player/media/audio_player/Song.wav" type="audio/wav">
I've been going crazy for the last day or so trying to figure out what is causing it not to work. I spent a lot of time trying to get it to source the correct path for the files but even though it seems to do that the files still can't be played.
I suspect that it could have something to to with passing the files into the template, from what I understand you should be able to pass a file as context right?
This is how my views are set up:
def ap(request):
context = {
"songs": Song.objects.all(),
}
return render(request, "audio_player/home.html",context)
Thankful for any help I can receive! Sorry for any eventual formatting errors and such...
Got it to work by setting these in settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
...and by adding this to my urls.py
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
...as well as changing my FileField Upload to
upload_to="audio_player/"
(Pretty much, just looking at the Django official docs again but being aware that I was not understanding things correctly and pretty much copying what it said straight up worked)
<div class="container">
{% for song in songs %}
<audio controls id="player">
<source src="{% if song.audio_file %}{{ song.audio_file.url }}{% endif %}" type="audio/wav">
</audio>
{% endfor %}
</div>
I wrote a python script that is creating switch configs out of .yaml files.
And I'm not sure how to create a web form that fits my needs.
I'm completely open on how to accomplish this. I just need a way to post values to my python script.
My HTML Form looks like this:
<form method="POST">
<input type="text" name="port"></input>
<input type="text" name="port.mode"></input>
</form>
The posted data gets into Flask like this:
[('port', 'Port1'), ('port.mode', 'Access')]
I'd like to have the data like this:
{ "ports": { "port1": {"mode": "Access"}}}
++Update
I'm already using Jinja to create the template.
Sample Jinja Template:
{%- for name,options in ports.items() %}
interface {{ name }}
{%- if options.mode == 'access' %}
switchport mode access
{% else %}
switchport mode trunk
{% endif %}
My Problem is between the HTML form and the template engine. I'm not sure how to model my HTML form to fit my needs.
2 ways I can think of accomplish this.
1. Alter the HTTP Post request in Javascript before submitting
2. Writing a sever-side python code to bring the HTTP Posted data into the correct form for my jinja Template.
But I' completely open to the method I use. I'm not limited to flask, jinja and python.
is this a solution?
In [1]: x = [('port', 'Port1'), ('port.mode', 'Access')]
In [2]: {x[0][0]: {x[0][1]: {x[1][0]: x[1][1]}}}
Out[2]: {'port': {'Port1': {'port.mode': 'Access'}}}
Hoping someone can help cure my stupidity. I am creating a webapp where I need to upload csv files and process them. I am struggling to get my code to work in its simplest form. I can get the page to load up but as soon as I press the submit button to post the file I get a 403 Forbidden Error: Access was denied to this resource.
When I run it in the google app interactive console it does not give me any errors. Can some one point me in the right direction please.
HTML:
{% extends base_layout %}
{% block header_title %}
{% trans %}Upload Documents{% endtrans %}
{% endblock %}
{% block content %}
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<br>
<input type="submit" name="submit" value="Submit">
{% endblock %}
Handler class:
class Upload(BaseHandler):
def get(self):
return self.render_template('upload.html')
def post(self):
file = self.request.POST.getall('myfile')
#file will be process with data going into models here.
self.response.out.write("success")
You cannot simply upload a file to app engine since the file system is read only. You have to upload to either cloud storage or blob storage. When using either you have to use the facilities for each.
The easiest and fastest way to upload files via a form is with the blobstore api.
Initial story
I'm trying to implement file upload using a simple form (I'm pasting stripped version, but all important parts are included):
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="up_file" size="50">
<input type="hidden" name="cpk" value="{{c.pk}}">
<input type="submit" name="btn_submit">
</form>
Now, server-side script running under wsgi was receiving strange values for "cpk" field and request.FILES was empty empty request.FILES and request.POST dictionaries, so I decided to switch to development server for debugging.
Surprisingly, ipdb debugger hangs after typing both request.POST and request.FILES and pressing enter... On the other hand, when I remove enctype="multipart/form-data" from tag, I'm able to check both request.POST and request.FILES, but of course request.FILES is empty then.
(Also wsgi version seems to be healed by removal of enctype="multipart/form-data"...)
Update
I tried all combinations of Opera 10//Firefox 3.5, enctype="multipart/form-data"//no multipart/form-data and dev server//mod_wsgi. The result is that it's enctype="multipart/form-data" that breaks the show. So now I'm going to check Django bugtracker if it's a known issue.
Meantime, maybe someone here can point me in the right direction
You may need to provide your view and form code as we use form uploads with enctype="multipart/form-data" in Django 1.1.1 with great success.
The following dummy app, for example, works perfectly in the dev server.
views.py
from django import forms
from django.shortcuts import render_to_response
class UploadForm(forms.Form):
cpk = forms.CharField(max_length=256)
f = forms.FileField()
def my_upload_view(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
print "Got cpk",form.cleaned_data['cpk']
print "Got file",request.FILES['f'].read()
else:
form = UploadForm()
return render_to_response('upload.html', {'form':form})
upload.html
<html>
<body>
<form enctype="multipart/form-data" method="post">
{{ form.f }}
{{ form.cpk }}
<input type="submit" />
</form>
</body>
</html>
I'm using the django form instance to render the file input, but it renders the very common <input type="file" name="f" id="id_f" />.
Using this sample, I get the content of the file (I've tested using a simple text file) printed to the terminal from my dev server. The few gotchas and tests I can recommend are:
ensure that the file you are uploading is less than settings.FILE_UPLOAD_MAX_MEMORY_SIZE (the default is 2.5 MB)
double-check that you haven't defined any custom file upload handlers that may be breaking the upload process (settings.FILE_UPLOAD_HANDLERS)
try uploading a very simple file (like a small text file) to see if the issue still persists with something basic
use a tool to inspect the raw HTTP request/response traffic (firebug will do this for you, and there are some stand-alone apps that will act as a proxy to help you here too)... sometimes the solution will jump out when you can see the raw traffic.
In case you haven't found them yet, the django file upload docs have a fair number of examples.