Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Need to know the process to implement perl script into web application server.

by chandantul (Scribe)
on Mar 29, 2021 at 17:38 UTC ( [id://11130547]=perlquestion: print w/replies, xml ) Need Help??

chandantul has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.
  • Comment on Need to know the process to implement perl script into web application server.

Replies are listed 'Best First'.
Re: Need to know the process to implement perl script into web application server.
by davido (Cardinal) on Mar 29, 2021 at 19:04 UTC

    You may want a Mojolicious::Lite application either running as a daemon, or you want a Mojolicious::Lite app running in CGI mode (for very low traffic sites, on providers where you can't run a daemon). The Mojolicious documentation provides very good tutorials. But it's going to require you do some learning on your own so that when you come to ask questions, they're based on a good understanding, and on you having the foundational knowledge that can only come from reading the manual and tutorials.

    I would start with: The Mojolicious Tutorial.

    Unrelated: We don't have a working familiarity that would justify you referring to me as "team".


    Dave

      Considering the poster's history and the amount of people who're doing his job for him (gratis) one can certainly understand his confusion . . .

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

Re: Need to know the process to implement perl script into web application server.
by choroba (Cardinal) on Mar 29, 2021 at 19:41 UTC
    Let's say your script looks like this:
    #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use Config::Tiny; my $config = 'Config::Tiny'->read('config.properties'); my $operand1 = $config->{operation}{op1}; my $operand2 = $config->{operation}{op2}; my $operation = $config->{operation}{op}; my $is_integer = $config->{operation}{int}; my %dispatch = ('+' => sub { $_[0] + $_[1] }, '-' => sub { $_[0] - $_[1] }, '/' => sub { $_[0] / $_[1] }, '*' => sub { $_[0] * $_[1] }); my $action = $dispatch{$operation} or die "Unknown operation '$operati +on'.\n"; my $result = $action->($operand1, $operand2); $result = int $result if $is_integer; say $result;

    A possible config file might look like

    [operation] op = / op1 = 10 op2 = 3 int = 1

    We will use the Dancer2 framework to help us with the work. It's not the only option, but we have to pick one, so why not this one. Install Dancer2 and App::Cmd from CPAN and run

    dancer2 gen -a webapp

    This creates a skeleton of the web application. For our simple script, we'll only need to handle two methods: get (which will display a form) and post (which will display the result). Each of them will have a different page template, so go to views/ and create query.tt:

    <form id="f1" method="post" action="/"> <div> <label for="op1">Op1</label> <input id="op1" name="op1"> <label for="op2">Op2</label> <input id="op2" name="op2"> </div> <div> <input type="radio" name="op" value="plus" id="plus"> <label for="plus">Plus</label> </div> <div> <input type="radio" name="op" value="minus" id="minus"> <label for="minus">Minus</label> </div> <div> <input type="radio" name="op" value="times" id="times"> <label for="times">Times</label> </div> <div> <input type="radio" name="op" value="divide" id="divide"> <label for="divide">Divide</label> </div> <div> <input type="checkbox" name="int" value="int" id="int"> <label for="int">Integer</label> </div> <button>Sumbit</button> </form>

    and result.tt:

    <p> Result: <% result %> </p>

    You see, all the parameters that were origianlly coming from the config will now come from the web form. Create the Op.pm in lib/ from the script:

    package Op; use warnings; use strict; my %dispatch = (plus => sub { $_[0] + $_[1] }, minus => sub { $_[0] - $_[1] }, divide => sub { $_[0] / $_[1] }, times => sub { $_[0] * $_[1] }); sub result { my ($args) = @_; my $operand1 = $args->{op1}; my $operand2 = $args->{op2}; my $operation = $args->{op}; my $is_integer = $args->{int}; my $action = $dispatch{$operation} or die "Unknown operation '$ope +ration'.\n"; my $result = $action->($operand1, $operand2); $result = int $result if $is_integer; return $result } __PACKAGE__

    Now just wire the routing in lib/webapp.pm:

    package webapp; use Dancer2; use Op; our $VERSION = '0.1'; get '/' => sub { template 'query' => { title => 'webapp' }; }; post '/' => sub { my $r = Op::result({op1 => param('op1'), op2 => param('op2'), int => param('int'), op => param('op')}); template result => { title => 'webapp', result => $r } }; true;

    Now, your application is ready to run. Launch

    plackup bin/app.psgi

    and open http://localhost:5000 in your browser.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Interesting, I never considered App::Cmd for such an application. It's my understanding that it's mean mainly for facilitating commandline utilities with subcommands. I suppose you can put a web face in front of anything, but I'll have to look a little more closely at what advantages it might provide. (Update) Oh, I see. I think you're listing that as s dependency on the dancer2 utility that comes with Dancer2?

      Hello Sir, As suggested, i was working with Dancer2. I am getting an error below after submitting required id and time and mail id.

      Please check below Web Form

      APPID Time in Hours Recipient Email Submit Powered by Dancer2 0.301001

      Please check below error.

      Error 500 - Internal Server Error Runtime Error Can't call method "content" on an undefined value at C:/Strawberry/per +l/site/lib/REST/Client.pm line 423.

      Please check below all my code snippet for query

      <form id="f1" method="post" action="/"> <div> <label for="oktaprev.APPID">APPID</label> <input id="oktaprev.APPID" name="oktaprev.APPID"> <label for="date.time">Time in Hours</label> <input id="date.time" name="date.time"> <label for="Email.id">Recipient Email</label> <input id="Email.id" name="Email.id"> </div> <button>Submit</button> </form>

      Please check below code snippet for result as suggested by you and i am wondering if its required for my purposes of not as i would like to generate the file after submitting the required details in web form and once the file generated , program sent an e-mail with generated file.

      <p> Result: <% result %> </p>

      Please check below Op.pm under /lib

      #!/usr/bin/env perl package Op; use strict; no warnings; use Win32::Process; ##use Net::LDAP; use REST::Client; use JSON::Parse ':all'; use MIME::Base64; use Term::ReadKey; use Data::Dumper; use MIME::Lite; use Net::SMTP; use Spreadsheet::XLSX; use Spreadsheet::ParseXLSX; use Excel::Writer::XLSX; use Config::Properties; use Data::Dumper; use List::Compare; use Array::Compare; use Storable qw/freeze/; use Data::Validate::IP; use Data::Table::Excel; use Excel::Writer::XLSX::Chart; use Win32::OLE::Const; use Spreadsheet::WriteExcel::Utility qw( xl_range_formula ); use Win32::OLE; use POSIX 'strftime'; use POSIX qw(strftime); use DateTime; use DateTime::Format::Strptime; use Try::Tiny; use feature qw{ say }; open my $fh, '<', "C:/PERL/" . "config.properties" or die "unable to o +pen configuration file"; my $properties = Config::Properties->new(); $properties->load($fh); my $value = $properties->getProperty('dev.token'); my $baseurl = $properties->getProperty('dev.baseURL'); sub result { my ($args) = @_; my $appID = $args->{APPID}; my $datver = $args->{datetime}; my $email = $args->{Email}; my $date3 = strftime '%Y-%m-%d' , localtime(time() - $datver*60*60 +); my $date4 = strftime '%Y-%m-%d' , localtime(time() - 24*60*60); my $apiurllog = $baseurl ."/users/sys/logs?"; my $client = REST::Client->new(); my @responsetext; my @responsetextall; my $sortor = "filter=eventType+eq+%22"; my $filter = "all.auth.sso"; my @$responsalter; sub api_call { $client->addHeader('Authorization',"SSWS $value"); $client->addHeader('Accept','application/json'); $client->addHeader('Content-type','application/json'); $client->GET($_[0]); } my $date2 = "%22&since=" . $date3 . "T00%3A00%3A00.000-04%3A00&until=" + . $date4 . "T23%3A59%3A59.000-04%3A00"; my $urlstringlog = $apiurllog . $sortor . $filter . $target . $appID . + $date2; run_api_call($urlstringlog); @responsetext = parse_json ($client->responseContent()); push @responsetextall, @responsetext; for my $i (0..$#responsetextall) { for my $j (0..$#{$responsetextall[$i]}) { my $responseid = $responsetextall[$i][$j]{act}{UID}; my $responsdisp = $responsetextall[$i][$j]{act}{Name}; push @$responsalter, $responseid ; } } my $workbook = Excel::Writer::XLSX->new( $strExcelFilename ); my $format_bold = $workbook->add_format( bold => 1, size => 10, top=> +1, bottom=> 1 ); my $format2 = $workbook->add_format(%header1); my $worksheet = $workbook->add_worksheet('UserSSO-Data'); my $r = 1; my $r2 = 1; my $r3 = 1; foreach my $j (0..$#responsalter ) { $worksheet->write(0, 0, 'UserSSO-Total +-Users' ); $worksheet->write($r2, 0, $responsalter[$j]); $r2 += 1; } $workbook->close; print "Spreadsheet saved.\n"; ## Mail Functionality my $msg = MIME::Lite->new ( From => $from_address, To => $to_address, Subject => $subject, Type =>'multipart/mixed' ) or die "Error creating multipart container: $!\n"; $msg->attach ( Type => 'text/csv', Encoding => 'base64', Path => $my_file_zip, Filename => $your_file_zip, Disposition => 'attachment' ) or die "Error adding $your_file_zip: $!\n"; MIME::Lite->send('smtp', $mail_host, Timeout=>60,Auth=>'LOGIN',AuthUs +er=>$from_address,AuthPass=>$pass,Port => 25, Debug => 1); } __PACKAGE__

      How can i achieve the goal for generating the report after submitting the details in web From.

        I'm not able to run the code. It doesn't even compile when I remove all the unused use clauses.

        Why do you turn warnings off? They would've told you

        Variable "$client" will not stay shared at Op.pm line 59.

        In Perl, nesting named subs doesn't make sense. Named subs exist in the namespace of the enclosing package, block scope doesn't influence them. It also means the closure is created around the $client variable from the first invocation of the outer sub.

        But you should fix all the remaining problems, too.

        Can't declare array dereference in "my" at Op.pm line 56, near "$respo +nsalter;" Global symbol "$target" requires explicit package name (did you forget + to declare "my $target"?) at Op.pm line 67. Global symbol "$strExcelFilename" requires explicit package name (did +you forget to declare "my $strExcelFilename"?) at Op.pm line 85. Global symbol "%header1" requires explicit package name (did you forge +t to declare "my %header1"?) at Op.pm line 87. Global symbol "@responsalter" requires explicit package name (did you +forget to declare "my @responsalter"?) at Op.pm line 94. Global symbol "@responsalter" requires explicit package name (did you +forget to declare "my @responsalter"?) at Op.pm line 98. Global symbol "$from_address" requires explicit package name (did you +forget to declare "my $from_address"?) at Op.pm line 112. Global symbol "$to_address" requires explicit package name (did you fo +rget to declare "my $to_address"?) at Op.pm line 113. Global symbol "$subject" requires explicit package name (did you forge +t to declare "my $subject"?) at Op.pm line 114. Global symbol "$my_file_zip" requires explicit package name (did you f +orget to declare "my $my_file_zip"?) at Op.pm line 121. Global symbol "$your_file_zip" requires explicit package name (did you + forget to declare "my $your_file_zip"?) at Op.pm line 122. Global symbol "$your_file_zip" requires explicit package name (did you + forget to declare "my $your_file_zip"?) at Op.pm line 124. Global symbol "$mail_host" requires explicit package name (did you for +get to declare "my $mail_host"?) at Op.pm line 126. Global symbol "$from_address" requires explicit package name (did you +forget to declare "my $from_address"?) at Op.pm line 126. Global symbol "$pass" requires explicit package name (did you forget t +o declare "my $pass"?) at Op.pm line 126. Execution of Op.pm aborted due to compilation errors.

        map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Need to know the process to implement perl script into web application server.
by hippo (Bishop) on Mar 30, 2021 at 08:56 UTC
    Do you have step by step process to achive the web interface functionality in perl script?

    Yes we do. See the Web Programming Tutorials.


    🦛

Re: Need to know the process to implement perl script into web application server.
by perlfan (Vicar) on Mar 29, 2021 at 19:55 UTC
    If you have an existing script, then I recommend converting it minimally to a modulino if you have not already done so. This will allow you to use it as a library in your (recommended) PSGI web facing application, while retaining your commandline usage.

    What is a modulino? It's simply a script that has a few extra lines in it + some judicious encapsulation of functionality into sub routines so that it can continue to function as the commandline utility you know, but provides a library interface as module. Just the first google hit, but this does a good job of outlining what it looks like https://perlmaven.com/modulino-both-script-and-module. Like I said, this can be done with minimal refactoring and can allow you to iteratively move towards creating bonefide Perl modules.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11130547]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-19 04:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found