Fetching images from URL and saving on server and/or Table (ImageField)

2024/11/13 22:51:40

I'm not seeing much documentation on this. I'm trying to get an image uploaded onto server from a URL. Ideally I'd like to make things simple but I'm in two minds as to whether using an ImageField is the best way or simpler to simply store the file on the server and display it as a static file. I'm not uploading anyfiles so I need to fetch them in. Can anyone suggest any decent code examples before I try and re-invent the wheel?

Given an URL say http://www.xyx.com/image.jpg, I'd like to download that image to the server, put it into a suitable location after renaming. My question is general as I'm looking for examples of what people have already done. So far I just see examples relating to uploading images, but that doesn't apply. This should be a simple case and I'm looking for a canonical example that might help.

This is for uploading an image from the user: Django: Image Upload to the Server

So are there any examples out there that just deal with the process of fetching and image and storing on the server and/or ImageField.

Answer

Well, just fetching an image and storing it into a file is straightforward:

import urllib2
with open('/path/to/storage/' + make_a_unique_name(), 'w') as f:f.write(urllib2.urlopen(your_url).read())

Then you need to configure your Web server to serve files from that directory.

But this comes with security risks.

A malicious user could come along and type a URL that points nowhere. Or that points to their own evil server, which accepts your connection but never responds. This would be a typical denial of service attack.

A naive fix could be:

urllib2.urlopen(your_url, timeout=5)

But then the adversary could build a server that accepts a connection and writes out a line every second indefinitely, never stopping. The timeout doesn’t cover that.

So a proper solution is to run a task queue, also with timeouts, and a carefully chosen number of workers, all strictly independent of your Web-facing processes.

Another kind of attack is to point your server at something private. Suppose, for the sake of example, that you have an internal admin site that is running on port 8000, and it is not accessible to the outside world, but it is accessible to your own processes. Then I could type http://localhost:8000/path/to/secret/stats.png and see all your valuable secret graphs, or even modify something. This is known as server-side request forgery or SSRF, and it’s not trivial to defend against. You can try parsing the URL and checking the hostname against a blacklist, or explicitly resolving the hostname and making sure it doesn’t point to any of your machines or networks (including 127.0.0.0/8).

Then of course, there is the problem of validating that the file you receive is actually an image, not an HTML file or a Windows executable. But this is common to the upload scenario as well.

https://en.xdnf.cn/q/119100.html

Related Q&A

Comparing list with a list of lists

I have a list string_array = [1, 2, 3, 4, 5, 6] and a list of lists multi_list = [[1, 2], [2, 3], [2, 4], [4, 5], [5, 6]]The first element of each sub-list in multi_list will have an associated entry …

Cannot save data to database Python

I have a table called category TABLES["category"] = ("""CREATE TABLE category (category_id INTEGER NOT NULL AUTO_INCREMENT,category_name VARCHAR(120) NOT NULL,PRIMARY KEY (cate…

How to generate a permutation of list of lists in python

I have a list of lists say[[2, 4, 6], [2, 6, 10], [2, 12, 22], [4, 6, 8], [4, 8, 12], [6, 8, 10], [8, 10, 12], [8, 15, 22], [10, 11, 12]]How do I generate a combination of the lists for a given length?…

Issue sending file via Discord bot (Python)

if message.content.upper().startswith("!HEADPATS"):time.sleep(1)with open(tenor.gif, rb) as picture:await client.send_file(channel, picture)Ive got my discord bot up and running (everythings …

Matplotlib installation on Mavericks

Im having problem while installing matplotlib. Im using Mavericks and it complains about a deprecated NumPy API both installing via pip and installing from source (following the instructions here https…

Exact string search in XML files?

I need to search into some XML files (all of them have the same name, pom.xml) for the following text sequence exactly (also in subfolders), so in case somebody write some text or even a blank, I must …

Integrate a function by the trapezoidal rule- Python

Here is the homework assignment Im trying to solve:A further improvement of the approximate integration method from the last question is to divide the area under the f(x) curve into n equally-spaced tr…

Kivy module not found in vscode (Mac)

I have installed Kivy and when I used the IDLE app that came with Python I can import it and it runs perfectly. However, when I try to import it in vscode I get the error: ModuleNotFoundError: No modul…

How to get latest unique entries from sqlite db with the counter of entries via Django ORM

I have a SQLite db which looks like this:|ID|DateTime|Lang|Details| |1 |16 Oct | GB | GB1 | |2 |15 Oct | GB | GB2 | |3 |17 Oct | ES | ES1 | |4 |13 Oct | ES | ES2 | |5 |15 Oct | ES | ES3 …

What does this code %.8f% do in python? [duplicate]

This question already has answers here:What does % do to strings in Python? [duplicate](4 answers)Closed 6 years ago.I am editing a code line to pass the rate in quotes:OO000OO00O0O0O000 [rate]=O0O0OO…