How to use PATCH method with CL_REST_HTTP_CLIENT? - rest

I am trying to consume an external REST service. Example:
DATA : lo_client TYPE REF TO if_http_client.
cl_http_client=>create_by_url(
EXPORTING
url = 'http://my_url'
IMPORTING
client = lo_client
EXCEPTIONS
argument_not_found = 1
plugin_not_active = 2
internal_error = 3
OTHERS = 4 ).
DATA(rest_client) = NEW CL_REST_HTTP_CLIENT( lo_client ).
rest_client->GET( ).
GET, POST, PUT and DELETE are Ok since they are implemented in the class CL_REST_HTTP_CLIENT.
Did anyone find a solution to use the PATCH method or how could I consume it otherwise?
PS: the constant for PATCH exists (if_rest_message=>gc_method_patch), but as I said, it's not implemented (send_receive).
Thank you.

You can use CL_HTTP_CLIENT to set method freely, CL_REST_HTTP_CLIENT is also using this class under the hood.
DATA : lo_client TYPE REF TO if_http_client.
cl_http_client=>create_by_url(
EXPORTING
url = 'http://my_url'
IMPORTING
client = lo_client
EXCEPTIONS
argument_not_found = 1
plugin_not_active = 2
internal_error = 3
OTHERS = 4 ).
lo_client->request->set_method( 'PATCH' ).
lo_client->request->set_content_type( 'application/json' ).
lo_client->send( ).
lo_client->receive(
EXCEPTIONS
http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3
OTHERS = 4 ).

It's not supported indeed. Quick and dirty way to get it to work is to copy the class and add the following method:
method PATCH.
send_receive( iv_http_method = if_rest_message=>gc_method_patch io_entity = io_entity ).
endmethod.

Related

QgsField won't accept parameter typeName

I'm trying to create new vector layer with the same fields as contained in original layer.
original_layer_fields_list = original_layer.fields().toList()
new_layer = QgsVectorLayer("Point", "new_layer", "memory")
pr = new_layer.dataProvider()
However, when I try:
for fld in original_layer_fields_list:
type_name = fld.typeName()
pr.addAttributes([QgsField(name = fld.name(), typeName = type_name)])
new_layer.updateFields()
QgsProject.instance().addMapLayer(new_layer)
I get a layer with no fields in attribute table.
If I try something like:
for fld in original_layer_fields_list:
if fld.type() == 2:
pr.addAttributes([QgsField(name = fld.name(), type = QVariant.Int)])
new_layer.updateFields()
QgsProject.instance().addMapLayer(new_layer)
... it works like charm.
Anyway ... I'd rather like the first solution to work in case if one wants to automate the process and not check for every field type and then find an appropriate code. Besides - I really am not able to find any documentation about codes for data types. I managed to find this post https://gis.stackexchange.com/questions/353975/get-only-fields-with-datatype-int-in-pyqgis where in comments Kadir pointed on this sourcecode (https://codebrowser.dev/qt5/qtbase/src/corelib/kernel/qvariant.h.html#QVariant::Type).
I'd really be thankful for any kind of direction.

Correct parameters for rotation using $BitmapDecoder.GetSoftwareBitmapAsync

I have this PowerShell code:
$AsyncTask = $BitmapDecoder.GetSoftwareBitmapAsync()
But discovered that some of the images coming in are rotated, so experimenting I came up with this:
$BmTf = [BitmapTransform]::new()
$BmTf.Rotation = [BitmapRotation]::None
# $BmTf.Rotation = [BitmapRotation]::Clockwise90Degrees
# $BmTf.Rotation = [BitmapRotation]::Clockwise180Degrees
# $BmTf.Rotation = [BitmapRotation]::Clockwise270Degrees
$AsyncTask = $BitmapDecoder.GetSoftwareBitmapAsync(
[BitmapPixelFormat]::Bgra8,
[BitmapAlphaMode]::Ignore,
$BmTf,
[ExifOrientationMode]::IgnoreExifOrientation,
[ColorManagementMode]::DoNotColorManage
)
While it does work, I'm not familiar BitmapPixelFormat, or the other parameters. The documentation for GetSoftwareBitmapAsync() doesn't appear to give any hints on what the default value it is using for BitmapPixelFormat.
Does anyone know the best values to pass to the version of GetSoftwareBitmapAsync() that takes 5 parameters to mimic the version of GetSoftwareBitmapAsync() that takes 0 parameters?
EDIT:
Just found out that trying [BitmapPixelFormat]::Unknown causes this error:
Exception calling "GetSoftwareBitmapAsync" with "5" argument(s): "The
parameter is incorrect. Windows.Graphics.Imaging: The bitmap pixel
format is unsupported."
But no errors with [BitmapPixelFormat]::Bgra8.
I don't know why GetSoftwareBitmapAsync doesn't like [BitmapPixelFormat]::Unknown, but here is the solution I found.
I need to first load the image to see if it needs rotating. That is done with the original command:
$AsyncTask = $BitmapDecoder.GetSoftwareBitmapAsync()
$SoftwareBitmap = GetAsync( $AsyncTask, ([SoftwareBitmap]) )
Then extract its BitmapPixelFormat:
$BitmapPixelFormat = $SoftwareBitmap.BitmapPixelFormat
And then use $BitmapPixelFormat for all calls to the 5 parameter version of GetSoftwareBitmapAsync().

OpenAPI 3 MicroProfile, using #SecurityRequirementSet in #OpenApiDefinition

I'm working on switching OpenAPI v2 to Open API 3, we'll be using MicroProfile 2.0 with Projects as the plugin that will generate the OAS from the code.
Now, we have different headers that are needed as a kind of authorization. I know I can put them on each resource, that seems just a lot of repetition, so I thought it was a good idea to put in the JaxRSConfiguration file as a #SecurityScheme and add them as security to the #OpenApiDefinition.
#OpenAPIDefinition(
info = #Info(
...
)
),
security = {
#SecurityRequirement(name = Header1),
#SecurityRequirement(name = Header2)
},
components = #Components(
securitySchemes = {
#SecurityScheme( apiKeyName = Header1 ... ) ,
#SecurityScheme( apiKeyName = Header2 ....)
}),
...
)
This is working, however it generates an OR, while it should be an AND (without the - )
security:
- Header1: []
- Header2: []
I thought I could use #SecurityRequirementsSet inside security in the #OpenApiDefinition, but unfortunately this is not allowed. I know I can use it on each call or on top of the class of the different calls but as this is still a sort of repetition, I would prefer to have it as a general authentication security.
Does anybody know how I can achieve this ?

PowerPoint REST API?

I'm looking for a REST API for generating PowerPoint slides... does anyone have any suggestions?
Realize this wouldn't be too difficult to implement, but we're trying to avoid building noncore functionality we could get from a third party.
Basically, we want to send a JSON blob and get back the generated slide.
Think this is a related question:
Is there an API to make a MS Office 365 Powerpoint presentation programmatically?
Thanks for your help!
You can try using Aspose.Slides Cloud for your purposes. This product provides REST-based APIs for many programming languages (C#, Java, PHP, Ruby, Python, Node.js, C++, Go, Perl, Swift), platforms and environments. With this product, you can use both Aspose file storages and third-party storages. Docker containers can also be used for working with Aspose.Slides Cloud.
This product does not support adding contents to presentations from JSON files but it provides many features for generating contents. It also provides features to add contents to presentations from HTML and PDF documents. The following Python sample code shows you how to add a WordArt object to a new presentation, for example.
import asposeslidescloud
from asposeslidescloud.apis.slides_api import SlidesApi
from asposeslidescloud.models.slide_export_format import SlideExportFormat
from asposeslidescloud.models.shape import Shape
from asposeslidescloud.models.fill_format import FillFormat
from asposeslidescloud.models.line_format import LineFormat
from asposeslidescloud.models.text_frame_format import TextFrameFormat
from asposeslidescloud.models.three_d_format import ThreeDFormat
from asposeslidescloud.models.shape_bevel import ShapeBevel
from asposeslidescloud.models.light_rig import LightRig
from asposeslidescloud.models.camera import Camera
slides_api = SlidesApi(None, "my_client_id", "my_client_secret")
file_name = "example.pptx"
slide_index = 1
dto = Shape()
dto.shape_type = "Rectangle"
dto.x = 100
dto.y = 100
dto.height = 100
dto.width = 200
dto.text = "Sample text"
dto.fill_format = FillFormat()
dto.fill_format.type = "NoFill"
dto.line_format = LineFormat()
dto.line_format.fill_format = FillFormat()
dto.line_format.fill_format.type = "NoFill"
text_frame_format = TextFrameFormat()
text_frame_format.transform = "ArchUpPour"
three_d_format = ThreeDFormat()
bevel_bottom = ShapeBevel()
bevel_bottom.bevel_type = "Circle"
bevel_bottom.height = 3.5
bevel_bottom.width = 3.5
three_d_format.bevel_bottom = bevel_bottom
bevel_top = ShapeBevel()
bevel_top.bevel_type = "Circle"
bevel_top.height = 4
bevel_top.width = 4
three_d_format.bevel_top = bevel_top
three_d_format.extrusion_color = "#FF008000"
three_d_format.extrusion_height = 6
three_d_format.contour_color = "#FF25353D"
three_d_format.contour_width = 1.5
three_d_format.depth = 3
three_d_format.material = "Plastic"
light_rig = LightRig()
light_rig.light_type = "Balanced"
light_rig.direction = "Top"
light_rig.x_rotation = 0
light_rig.y_rotation = 0
light_rig.z_rotation = 40
three_d_format.light_rig = light_rig
camera = Camera()
camera.camera_type = "PerspectiveContrastingRightFacing"
three_d_format.camera = camera
text_frame_format.three_d_format = three_d_format
dto.text_frame_format = text_frame_format
# Create the WordArt object and download the presentation.
slides_api.create_presentation(file_name)
slides_api.create_shape(file_name, slide_index, dto)
file_path = slides_api.download_file(file_name)
The WordArt object in the output presentation:
This is a paid product but you can make 150 free API calls per month for API learning and presentation processing.
I work as a Support Developer at Aspose.

cgi.parse_multipart function throws TypeError in Python 3

I'm trying to make an exercise from Udacity's Full Stack Foundations course. I have the do_POST method inside my subclass from BaseHTTPRequestHandler, basically I want to get a post value named message submitted with a multipart form, this is the code for the method:
def do_POST(self):
try:
if self.path.endswith("/Hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ""
output += "<html><body>"
output += "<h2>Ok, how about this?</h2>"
output += "<h1>{}</h1>".format(messagecontent)
output += "<form method='POST' enctype='multipart/form-data' action='/Hello'>"
output += "<h2>What would you like to say?</h2>"
output += "<input name='message' type='text'/><br/><input type='submit' value='Submit'/>"
output += "</form></body></html>"
self.wfile.write(output.encode('utf-8'))
print(output)
return
except:
self.send_error(404, "{}".format(sys.exc_info()[0]))
print(sys.exc_info() )
The problem is that the cgi.parse_multipart(self.rfile, pdict) is throwing an exception: TypeError: can't concat bytes to str, the implementation was provided in the videos for the course, but they're using Python 2.7 and I'm using python 3, I've looked for a solution all afternoon but I could not find anything useful, what would be the correct way to read data passed from a multipart form in python 3?
I've came across here to solve the same problem like you have.
I found a silly solution for that.
I just convert 'boundary' item in the dictionary from string to bytes with an encoding option.
ctype, pdict = cgi.parse_header(self.headers['content-type'])
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
In my case, It seems work properly.
To change the tutor's code to work for Python 3 there are three error messages you'll have to combat:
If you get these error messages
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
AttributeError: 'HTTPMessage' object has no attribute 'getheader'
or
boundary = pdict['boundary'].decode('ascii')
AttributeError: 'str' object has no attribute 'decode'
or
headers['Content-Length'] = pdict['CONTENT-LENGTH']
KeyError: 'CONTENT-LENGTH'
when running
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
if c_type == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, p_dict)
message_content = fields.get('message')
this applies to you.
Solution
First of all change the first line to accommodate Python 3:
- c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
+ c_type, p_dict = cgi.parse_header(self.headers.get('Content-Type'))
Secondly, to fix the error of 'str' object not having any attribute 'decode', it's because of the change of strings being turned into unicode strings as of Python 3, instead of being equivalent to byte strings as in Python 3, so add this line just under the above one:
p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
Thirdly, to fix the error of not having 'CONTENT-LENGTH' in pdict just add these lines before the if statement:
content_len = int(self.headers.get('Content-length'))
p_dict['CONTENT-LENGTH'] = content_len
Full solution on my Github:
https://github.com/rSkogeby/web-server
I am doing the same course and was running into the same problem. Instead of getting it to work with cgi I am now using the parse library. This was shown in the same course just a few lessons earlier.
from urllib.parse import parse_qs
length = int(self.headers.get('Content-length', 0))
body = self.rfile.read(length).decode()
params = parse_qs(body)
messagecontent = params["message"][0]
And you have to get rid of the enctype='multipart/form-data' in your form.
In my case I used cgi.FieldStorage to extract file and name instead of cgi.parse_multipart
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print('File', form['file'].file.read())
print('Name', form['name'].value)
Another hack solution is to edit the source of the cgi module.
At the very beginning of the parse_multipart (around the 226th line):
Change the usage of the boundary to str(boundary)
...
boundary = b""
if 'boundary' in pdict:
boundary = pdict['boundary']
if not valid_boundary(boundary):
raise ValueError('Invalid boundary in multipart form: %r'
% (boundary,))
nextpart = b"--" + str(boundary)
lastpart = b"--" + str(boundary) + b"--"
...