django upload file using JSON - json

i have JSON request like this:
object: { "fields":{ "src" : "http://dss.com/a.jpg", "data" : " //file is here" } }
i have the model like this:
class FileMy(models.Model):
f = models.FileField(upload_to='file_path/',)
How to save the file ?

You may use urllib to read the file and then you can add it to your model.
Take a look at this post:
Django: add image in an ImageField from image url

You may be able to wrap the data in a ContentFile which inherits from File and then save the file to the model directly.
from __future__ import unicode_literals
from django.core.files.base import ContentFile
from .models import FileMy
f1 = ContentFile("esta sentencia está en español")
f2 = ContentFile(b"these are bytes")
m1 = FileMy()
m2 = FileMy()
m1.f.save("filename", f1, save=True)
m2.f.save("filename", f2, save=True)

First of all, encode the raw data in the json request body.
from tempfile import NamedTemporaryFile
from django.core.files import File
def save_file_to_field(field, file_name, raw_content):
# field: reference to the model object instance field
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(raw_content)
field.save(
file_name,
File(img_temp)
)
img_temp.flush()
What does this do:
creates a temporary file on your system that holds the data
uses the file field save method to trigger the usual file handling
deletes the temporary file

Related

How can I get data from external API JSON file in ODOO

[{"Id":"605a321e-7c10-49e4-9d34-ba03c4b34f69","Url":"","Type":"INBOUND_OUTBOUND",
"ClearCurrentData":true,"FillOutFormFields":true,"RequestProtocol":"HTTP_REQUEST",
"FileToSend":"NONE","SendDefaultData":false,"SendDetectionData":false,"ShowDialogMessage":false,"IsActive":false,"SendingTrigger":"MANUALLY","TCPSocketMethod":"","TriggerButtonName":"Get data"}]
This is an External API Call JSON file how can i get the data in ODOO Any Solutions please ?
Mentioned Above code API JSON file
i had only External JSON File,don't have a table name & Database name is it possible to get data in ODOO
create a model for this data for example
class apiCall(models.Model):
_name = 'apiCall.api'
id = fields.Char(string='Id')
url = fields.Char(string='url')
#api.model
def call_api(self):
### result of calling external api is "result"
for line of self:
id = result[0].Id
url = result[0].url
You can call a method on button click and access the json file. Below is the code for accessing json file:-
import json
def api_call(self):
# Opening JSON file
f = open('file_name.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in self:
print(i)
# Closing file
f.close()
Below is the button code which is applied in xml file:-
<button name="api_call" type="object" string="Call API" class="oe_highlight" />
by this way you can call the json file with external api in odoo.
In your custom module (my_custom_module), move your json file to its subdirectory static/src:
import json
from odoo.modules.module import get_module_resource
def call_api(self)
json_filepath = get_module_resource('my_custom_module', 'static/src/', 'my_api_cred.json')
with open(json_filepath) as f:
data = json.load(f)

Azure Function in Python get schema of parquet file

It is possible get schema of parquet file using Azure Function in Python without download file from datalake ? I using BlobStorageClient to connect to data lake and get the files and containers but i have no idea how can i dispatcher the command using for example pyarrow.
About pyarrow: https://arrow.apache.org/docs/python/parquet.html
BlobStorageClient: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python-legacy
Regarding the issue, please refer to the following script
import pyarrow.parquet as pq
import io
from azure.storage.blob import BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_string(conn_str)
container_client = blob_service_client.get_container_client('test')
blob_client = container_client.get_blob_client('test.parquet')
with io.BytesIO() as f:
download_stream = blob_client.download_blob(0)
download_stream.readinto(f)
schema = pq.read_schema(f)
print(schema)
It is possible to read both parquet schema and parquet metadata without reading the file content using read_schema and read_metadata:
import pyarrow.parquet as pq
fname = 'filename.parquet'
meta = pq.read_metadata(fname)
schema = pq.read_schema(fname)

How to read CSV file from device storage in flutter

I want to import data into firebase database from a CSV file in flutter. So I pick .CSV file from device using file picker. Now how can I read data from that file?
At first import file_picker and CSV package from dart packages. Than define the method pickFile() as i have given below. it will pick the file from device storage and after selection it will print data. pickFile() funtion shoulb be called to get result.
import 'package:file_picker/file_picker.dart';
import 'package:csv/csv.dart';
import 'dart:convert' show utf8;
pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles();
if (result != null) {
PlatformFile file = result.files.first;
final input = new File(file.path).openRead();
final fields = await input
.transform(utf8.decoder)
.transform(new CsvToListConverter())
.toList();
print(fields);
}
}

How to read local json import in flutter?

I have a JSON file in the flutter directory, not in assets.
json_data.json:-
{
"foo" : "bar"
}
I want to read this JSON on different files.
like
myfile.dart:-
import "package:mypackage/json_data.json" as data;
import 'dart:convert';
var my_data = json.decode(data);
I am getting the error:-
The name 'data' refers to an import prefix, so it must be followed by '.'.
Try correcting the name to refer to something other than a prefix, or renaming the prefix.
What is the problem here? why can't I read JSON from local import in flutter?
You should look into loading assets in flutter. You can't simply import an arbitrary file. Importing is for source code/libraries.
You need to declare this file as an asset in your pubspec.yaml
flutter:
assets:
- json_data.json
Then in your code you can load this asset as a String:
import 'package:flutter/services.dart' show rootBundle;
Future<String> getJson() {
return rootBundle.loadString('json_data.json');
}
You can decode the JSON with your existing code, but it should be placed in a method body somewhere. You call this getJson function to retrieve the JSON String:
var my_data = json.decode(await getJson());
Alternatively, you could simplify this even further by putting the contents of your JSON file directly into the code as a String, but this may not be possible, it depends on your intended use of this JSON.
const String data = '''
{
"foo" : "bar"
}
''';
var my_data = json.decode(data);

How can I pass a .txt file as a function parameter

Say I have a function that reads a .txt file and creates arrays based on the columns of the data within that file. What I have right now inside the function looks like:
data = open("some_file_name.txt","r")
But if I want to change the .txt file that the function reads I have to manually go into the code and type in the new file name before running it again. Instead, how can I pass any file name to the function so it looks like:
my_function(/filepath/some_file_name.txt):
data = open("specified_file_name.txt","r")
I think you want
def my_function(filepath):
data = open(filepath, "r")
...
and then
my_function("/filepath/some_file_name.txt")
or better:
def my_function(data):
...
and then
with open("/filepath/some_file_name.txt", "rb") as data:
my_function(data)
The latter version lets you pass in any file-like object to my_function().
Update: if you want to get fancy and allow file names or file handles:
def my_func(data):
if isinstance(data, basestring):
with open(data, 'rb') as f:
return my_func(f)
...