I want to put a file (file.img) as a POST data content, so if the file is in the same folder as the script, is $req->content(file.img); valid ?
Cheers
This seems to be something that you could easily test for yourself rather than asking us. What happened when you tried it?
(I'm going to assume that $req is an HTTP::Request object - I don't know why you wouldn't include that information in your question).
In short, no, it's not valid. And it's not valid for a number of reasons.
It's not valid because file.img would be interpreted as the bareword file concatenated with the bareword img - which would give the string fileimg.
It's not valid because use strict makes barewords illegal, so if you're using use strict (and you really should be) your code won't even compile.
It's not valid because HTTP::Request::content expects a sequence of bytes. So even if you didn't use use strict all this code would do would be to add the string fileimg to the request body.
If you want to add the contents of the file to the body, then you need to open the file, read in the data and then pass that data to content.
This is all explained in the documentation for HTTP::Request.
Related
In my rest-api, I am using regexes. For querying the server, I normally use GET. However, there is the regex situation. With nearly all characters (even those that normally have to be escaped, like '['), this works just fine when using it in the address line, however, with '+', it doesn't. I am thinking about using a POST request instead so I can just specify the regex the body and don't have to escape anything. However, officially, POST requests are only used when changing something. Would it be bad to use a POST request here? Or is there a better solution?
Would it be bad to use a POST request here?
If you can use a GET for a safe request, you should do that.
With nearly all characters (even those that normally have to be escaped, like '['), this works just fine when using it in the address line, however, with '+', it doesn't.
+ means something magic in an application/x-www-form-urlencoded string (see details here); if you are using a decoding function to get the data out of your url, but are not encoding that data when you copy it into the url, then you aren't going to have a good time.
If your encoders and decoders are correctly balanced, using GET should not be a problem.
Well, my 'encoder' in this case would be a human typing something into the address bar...
And that's fine, provided that you don't use a decoder to parse the information you get on the server end. That may mean that you need to parse the path/query by hand, rather than using "standard" library calls to do it.
I have a perl script that connects to the Plex API. It logs in and performs certain actions (mostly working).
However, the Plex API suggests (insists?) that each instance of the script send a unique ID, such that if I share this script with anyone else they should use a different string.
In the interests of keeping this simple, I don't want to have some configuration file that keeps that value outside of the script. I also can't leave a value hard-coded in, no one who downloads this will change it.
Could the perl script modify itself?
If I were to declare it as such:
my $uuid = 1;
... then could I not check immediately afterward if this value is equal to 1, and if so overwrite that with a randomly generated uuid? The script would then exit, but somehow re-invoke itself (so the user doesn't have to run it a second time).
Is there a safe way to do this? Alternatively, is there a better way to accomplish the goal without using this method?
Make the last line of your script __DATA__ and append the ID to the script either at installation or first run. Reading from the special <DATA> handle reads the data segment of a script.
You could use UUID::Tiny to generate a random UUID:
use UUID::Tiny;
my $uuid = create_UUID(UUID_V4);
To preserve the UUID between invocations, you'll have to modify the script itself. The answers in this thread might be helpful.
Update
You say in the comments that you want a different unique ID "per installation", but you also say that "it needs to be the same value for any given user", so I'm no longer sure that my answer will satisfy your requirements
I suggest that you use the system UUID returned by dmidecode. Of course you will need to have it installed on your computer, and there's a parser module for it on CPAN called Parse::DMIDecode
It's slightly more complex if you have to support Windows systems. You can use DmiDecode for Windows, which is available as a ready-built binary, but the parser module explicitly checks that there are no colons (amongst other things) in the path to the demidecode executable, so a call to the probe method won't work. Instead you must call demidecode and pass the result to the parse method
This short example works fine on both Linux and Windows
use strict;
use warnings 'all';
use feature 'say';
use Parse::DMIDecode;
my $decoder = Parse::DMIDecode->new;
$decoder->parse(qx{dmidecode});
say $decoder->keyword('system-uuid');
output
35304535-3439-4344-3232-3245FFFFFFFF
I need to handle some HTTP URLs in a Perl program, but I have doubts how should the URI class help me.
Particularly, I'd like the to use the URI class for resolving relative URLs and getting their components. However, the problems are:
I need a function to work with both URI objects and URI strings as arguments (or ensure only one gets passed)
sub foo_string_or_url {
my $uri = URI->new(shift);
is that the right approach? I don't quite like it, because it stringifies the URI and creates new object unnecessarily.
Extract the components
my $host = $uri->host;
This is also problematic, because not all URIs have host, particularly, if someone passes garbage to the function, this will die().
Resolve a relative URL
my $new_url = URI::URL->new($uri, $base)->abs;
IIUC, without the ->abs, the result will still stringify to the relative URL (and will not work for HTTP::Requests), am I right? Also, is this guaranteed to return a URI?
How should I handle these problems? The possibilities are
Use ->isa('URI') and ->can("host") all the time
Seems error prone and ugly to me
Don't use URI class at all and parse URLs using regexes
I'd still rather use a library solution than debug my own
Wrap URI operations in try { ... } catch { ... }
see the first point
Is there a sane, fool-proof way of using the URI classes? Something simple I haven't thought of (in the list above)?
I think your question can be summarised: parameter validation is tedious, what do I do about it?
I don't like it, either. This is a matter of differing opinion among developers, other say coercions are better than sliced bread, especially when automatically done by Moose. I argue that allowing only one type of simplifies the program. Also, YAGNI applies in the vast majority of cases. Reject wrong types, employ a helper module such as Params::Validate/MooseX::Method::Signatures/MooseX::Declare in order to avoid the manual checks as shown in your code samples.
This is the desired behaviour. Exception handling mechanisms let you write custom code appropriate for each situation. If you think it's not aesthetically pleasing, remove it and mind the consequences of letting exceptions go unchecked.
use Try::Tiny;
my $host;
try {
$host = $uri->host;
} catch {
warn "Could not determine host for $uri. Message was: $_. Retry/abort/ignore?\n";
…
};
Yes and yes.
I've got a setup where I use doxygen to describe a set on unit tests (I use QtTest to run the tests). The output from the tests are parsed by a little Python snippet that produces a nice and tidy report. Now, I'd love to link from the report to each test case, i.e. private slot member method, in the doxygen material. However, the anchors defined by doxygen looks like this:
<a class="anchor" id="a2a0e066d4dad8e0dff6c9231bf65fd65"></a>
<!-- doxytag: member="PRadioTunerTst::scanFM" ref="a2a0e066d4dad8e0dff6c9231bf65fd65" args="()" -->
Sure, I could parse the doxygen html and match all method to the reference key, but I'd much rather have readable links. I do not overload any unit test case methods, so having them enumerated would not be an issue - I'd simply be able to pick the first and only. I'd even be happy to calculate the id hash myself. I just need to know how to.
So, basically, the questions is:
Does anyone know how to tune doxygen
to generate readable anchors
if not, how do I calculate the hash?
Instead of trying to reconstruct the hash (which is a md5 checksum over the method's definition as parsed by doxygen, see MemberDef::setAnchor() in the code). I would suggest to let doxygen generate a tag file (GENERATE_TAGFILE) and then parse that. The tag file is a simple XML file which has both the name and the anchor for each member.
I also needed link targets, in my case for rst docs to point at breathe/doxygen-created html. Here's what I did:
To better understand how doxygen creates anchors, I recompiled doxygen, with this at the end of setAnchor():
printf("memAnchor=%s sigStr=%s\n", memAnchor.data(), sigStr.data());
, which creates output like:
memAnchor=const int SomeNamespace::GetStateGetState(SomeNamespace::State *state) sigStr=f2c41a8a6a152602c92fefb80bd0862a
I already had my function signatures, so I created strings similar to memAnchor above and piped it through md5sum to get the hash, then appended it to the string which is common to all anchors. In my rst doc, I then put definitions like:
.. _GetState: `project0class_SomeNamespace_1f2c41a8a6a152602c92fefb80bd0862a`_
Not sure on the first question about readable anchors.
I have seen the examples of Net::OpenID::Consumer::Lite on CPAN but I was hoping to get a single script that uses POST method. If nobody has this than I will post my solution back here once I get it working.
This seems to be the only applicable test in the manifest and it doesn't seem too useful
http://cpansearch.perl.org/src/TOKUHIROM/Net-OpenID-Consumer-Lite-0.02/xt/001_mixi.t Apache2::AuthMixi also uses it a bit
This module simply delegates to LWP::UserAgent. I don't like it, it should subclass LWP::UserAgent instead of delegating. You can find the docs for LWP::UserAgent on cpan, and access the base copy through the hidden method _ua (though, by convention, the preceding underscore tells you it isn't supported and it is supposed to be kept secret)
my $csr = Net::OpenID::Consumer::Lite->new();
$csr->_ua->post(); # same as LWP::UserAgent::post()
It seems as if you're supposed to use only handle_server_response() which calls _check_authentication() which calls _get() which delegates to ->_ua->get().
check_authentication() wants an HashRef jump-table with 5 events for not_openid, setup_required, cancelled, verified, and error. In addition I believe it wants a bunch of key (openid.) prefixed stuff, and values.
Per the code, for a request to be sent $request->{'openid.mode'} must exist in the $request and be set (preferably to) check_authentication, and not set to 'cancel'. The openid.user_setup_url key must logically not be set or it will just call the respective callback. It must also have an op_endpoint.endpoint key set, which is where the request is destined to go.
This code isn't hard to read, I'd suggesting taking a look The author also seems to have a bunch of modules which is a good sign. I don't like jump-tables with data like that, it seems kind of weird from a UI perspective.