How to upload the image with it's encoding binary data?
I have the ASCII characters of a image binary data and can upload this image to some URL use the code below:
ASCII_CHARACTERS = ......
URL = ...
with open('z.jpg','wb+') as f:
f.write(base64.b64decode(ASCII_CHARACTERS))
f.seek(0)
r = requests.post(URL, files={'media':f})
This code is workable but have to write this image to disk first. Can I fix this code and upload it without writing step?
Thanks.
See also questions close to this topic
-
How to decode an encoded zipfile using Python?
I have a base64 encoded zip file. I am able to convert that zip file and then extract its content using Windows commandline. I have been trying to do the same with Python, but unsuccessful. Could you please help me? When I run the following code:
import base64 import codecs import zlib import io, zipfile, json, pprint d = open("data.txt", "rb").read() #dd = base64.decodestring(d) #print(dd) z = zipfile.ZipFile(io.BytesIO(d)) unpack = zlib.decompress(d)
I get the following error:
raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file
The data.txt file contains the base64 string:
-
Base64 does not encode the entire string
When I encode tex, for some reason it cuts off part of the string ... What could be the problem?
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH); Date date = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.HOUR,+ 9); String server_time = dateFormat.format(calendar.getTime()); String wmsAuthSign = "server_time=" + server_time + "&hash_value=U2QK9TLB55JWTZr3OKZHtg==&validminutes=120"; wmsAuthSign = "?wmsAuthSign=" + Base64.encodeToString(wmsAuthSign.getBytes(), Base64.DEFAULT);
I am submitting something like this:
server_time=02/18/2019 23:38:43 PM&hash_value=U2QK9TLB55JWTZr3OKZHtg==&validminutes=120
And if you decode the encoded text, you get a trimmed result:
server_time=02/18/2019 23:38:43 PM&hash_value=U2QK9TLB55J
-
How to Convert Base64 string To Video in C#
I'm trying to convert a
base64
string to video In C#, and save it in the App_Data/Video/Film folder . It's not working.Code:
public void ConvertToVideo(string data) { byte[] ret = Convert.FromBase64String(data); string date = DateTime.Now.ToString().Replace(@"/", @"_").Replace(@":", @"_").Replace(@" ", @"_"); string path = HttpContext.Current.Server.MapPath("~/App_Data/Video/Film"); FileInfo fil = new FileInfo(path+date+".mp4"); using (Stream sw = fil.OpenWrite()) { sw.Write(ret, 0, ret.Length); sw.Close(); } }
Error: The input is not a valid Base-64 String as it contain...
-
how to use requests raise error in python
Iam using python to fetch content from some urls. So I have a list of urls, and all are fine except one of them where I get a 404. I wanted to fetch this like:
for url in urls: r = requests.get(url) try: r.raise_for_status() except RuntimeError: print('error: could not get content from url because of {}'.format(r.status_code))
But now, the exception raised by raise_for_status() is not fetched but just printed out? How can I print my own error code if its raised?
-
I would like to calculate an extrema (maximum, minimum) in a given interval but there is a TypeError
I develop a program which can find roots, extrema etc.... (I use Thonny): "TypeError: 'Integer' object does not support indexing".
In my program you enter any function and the program calculates the extrema. I use
sympy
. My code isn't very long so I included everything.Thanks for any tips and answers.
edit:
Maybe its a little hard to understand my program without an explaination: First the user types in any function. Then he adds an interval (xmin
,xmax
).
Usingf=S(funk...)
I change the typed in function to somethingsympy
can understand. Thensympy
calculates the first and second differentiation usingdiff
.Using
solve
sympy
calculates the roots fromf_diff_1
and puts them in a list.
There is a loop wheresympy
calculatesy
(y_0=f.subs(x, x_0[i])
) and afterwards there is an another loop where everyx
andy
is displayed if it is located within the interval.from sympy import* x=Symbol("x") #Funktion eingeben Funktion=input("Funktion eingeben: ") xmin=float(input("Grenzwert links: ")) xmax=float(input("Grenzwert rechts: ")) #eingegebene Funktion für Sympy umwandeln, damit Sympy sie als Funktion erkennt f=S(Funktion) #erste und zweite Ableitung f_diff_1=diff(f, x) f_diff_2=diff(f, x) #Extrempunkte bestimmen extrema=solve(Eq(f_diff_1, x)) x_0=extrema Anzahl_1=len(x_0) for i in range (Anzahl_1): y_0=f.subs(x, x_0[i]) for a in range (Anzahl_1): if xmin<=x_0[a] and xmax>=x_0[a]: #print(f"Der Hochpunkt liegt bei: ({x_0[a]}| {y_0[a]})") print("Extrempunkt liegt bei", x_0[a], y_0[a])
-
Constructing python request using certificate
I need to access Splunk from python. My Splunk admin said the user / password authentication is not possible, I have to use the certificate. I would need help to construct my request in python provided I have the certificate of the user (C5271127) in hand. At the moment my code looks as follows:
import urllib import urllib.parse import urllib.request as urllibrequest import requests import re from xml.dom import minidom def pretty_print_POST(req): """ At this point it is completely built and ready to be fired; it is "prepared". However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request. """ print('{}\n{}\n{}\n\n{}'.format( '-----------START-----------', req.method + ' ' + req.url, '\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()), req.body, )) base_url = 'https://splunk.mo.sap.corp:8089' username = 'C5271127' password = 'XXXX' search_query = "search=savedsearch BWP_nodes_in_sync" # encoded = urllib.parse.urlencode(({password}).encode('utf8')) # print (urllib.parse.urldecode(password)) # Login and get the session key request = urllibrequest.Request(base_url + '/servicesNS/admin/search/auth/login', data = urllib.parse.urlencode({'username': username, 'password': password}).encode("utf-8")) #prepared = request.prepare() #pretty_print_POST(request) server_content = urllibrequest.urlopen(request) session_key = minidom.parseString(server_content.read()).\ getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue print ("Session Key: %s" % session_key) # Perform a search r = requests.post(base_url + '/services/search/jobs/', data=search_query, headers = { 'Authorization': ('Splunk %s' %session_key)}, verify = False) print (r.text.split('\n')[1]) prog = re.compile(r'[^\d]+(\d+\.\d+)[^\d]+') id = prog.match(r.text.split('\n')[1]).group(1) print (base_url + '/services/search/jobs/%s/results' % id) r = requests.get(base_url + '/services/search/jobs/%s/results' % id, data="output_mode=csv", headers = { 'Authorization': ('Splunk %s' %session_key)}, verify = False) print (r.text)
As mentioned, only the certificate logon is possible, so I get the error:
RLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)>
I need help with building the request using the certificate. I can extract it from browser for the user C5271127. How the proper code would look like?
Kind Regards, Kamil