Peter Siebel - Practical Common Lisp

Здесь есть возможность читать онлайн «Peter Siebel - Practical Common Lisp» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2005, ISBN: 2005, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Practical Common Lisp: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Practical Common Lisp»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Practical Common Lisp — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Practical Common Lisp», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

(defun simple-form (request entity)

(with-http-response (request entity :content-type "text/html")

(with-http-body (request entity)

(let ((*html-output* (request-reply-stream request)))

(html

(:html

(:head (:title "Simple Form"))

(:body

(:form :method "POST" :action "/show-query-params"

(:table

(:tr (:td "Foo")

(:td (:input :name "foo" :size 20)))

(:tr (:td "Password")

(:td (:input :name "password" :type "password" :size 20))))

(:p (:input :name "submit" :type "submit" :value "Okay")

(:input ::type "reset" :value "Reset"))))))))))

(publish :path "/simple-form" :function 'simple-form)

Point your browser to http://localhost:2001/simple-form, and you should see a page like the one in Figure 26-5.

Figure 26-5. http://localhost:2001/simple-form

If you fill in the form with the "abc" and "def" values, clicking the Okay button should take you to a page like the one in Figure 26-6.

Figure 266 Result of submitting the simple form However most of the time - фото 16

Figure 26-6. Result of submitting the simple form

However, most of the time you won't need to iterate over all the query parameters; you'll want to pick out individual parameters. For instance, you might want to modify random-numberso the limit value you pass to RANDOM can be supplied via a query parameter. In that case, you use the function request-query-value, which takes the request object and the name of the parameter whose value you want and returns the value as a string or NIL if no such parameter has been supplied. A parameterizable version of random-numbermight look like this:

(defun random-number (request entity)

(with-http-response (request entity :content-type "text/html")

(with-http-body (request entity)

(let* ((*html-output* (request-reply-stream request))

(limit-string (or (request-query-value "limit" request) ""))

(limit (or (parse-integer limit-string :junk-allowed t) 1000)))

(html

(:html

(:head (:title "Random"))

(:body

(:p "Random number: " (:print (random limit))))))))))

Because request-query-valuecan return either NIL or an empty string, you have to deal with both those cases when parsing the parameter into a number to pass to RANDOM . You can deal with a NIL value when you bind limit-string, binding it to ""if there's no "limit" query parameter. Then you can use the :junk-allowedargument to PARSE-INTEGER to ensure that it returns either NIL (if it can't parse an integer from the string given) or an integer. In the section "A Small Application Framework," you'll develop some macros to make it easier to deal with grabbing query parameters and converting them to various types.

Cookies

In AllegroServe you can send a Set-Cookie header that tells the browser to save a cookie and send it along with subsequent requests by calling the function set-cookie-headerwithin the body of with-http-responsebut before the call to with-http-body. The first argument to the function is the request object, and the remaining arguments are keyword arguments used to set the various properties of the cookie. The only two you must pass are the :nameand :valuearguments, both of which should be strings. The other possible arguments that affect the cookie sent to the browser are :expires, :path, :domain, and :secure.

Of these, you need to worry only about :expires. It controls how long the browser should save the cookie. If :expiresis NIL (the default), the browser will save the cookie only until it exits. Other possible values are :never, which means the cookie should be kept forever, or a universal time as returned by GET-UNIVERSAL-TIME or ENCODE-UNIVERSAL-TIME . An :expiresof zero tells the client to immediately discard an existing cookie. [290] For information about the meaning of the other parameters, see the AllegroServe documentation and RFC 2109, which describes the cookie mechanism.

After you've set a cookie, you can use the function get-cookie-valuesto get an alist containing one name/value pair for each cookie sent by the browser. From that alist, you can pick out individual cookie values using ASSOC and CDR .

The following function shows the names and values of all the cookies sent by the browser:

(defun show-cookies (request entity)

(with-http-response (request entity :content-type "text/html")

(with-http-body (request entity)

(with-html-output ((request-reply-stream request))

(html

(:standard-page

(:title "Cookies")

(if (null (get-cookie-values request))

(html (:p "No cookies."))

(html

(:table

(loop for (key . value) in (get-cookie-values request)

do (html (:tr (:td key) (:td value)))))))))))))

(publish :path "/show-cookies" :function 'show-cookies)

The first time you load the page http://localhost:2001/show-cookiesit should say "No cookies" as shown in Figure 26-7 since you haven't set any yet.

Figure 267 httplocalhost2001showcookies with no cookies To set a - фото 17

Figure 26-7. http://localhost:2001/show-cookies with no cookies

To set a cookie, you need another function, such as the following:

(defun set-cookie (request entity)

(with-http-response (request entity :content-type "text/html")

(set-cookie-header request :name "MyCookie" :value "A cookie value")

(with-http-body (request entity)

(with-html-output ((request-reply-stream request))

(html

(:standard-page

(:title "Set Cookie")

(:p "Cookie set.")

(:p (:a :href "/show-cookies" "Look at cookie jar."))))))))

(publish :path "/set-cookie" :function 'set-cookie)

If you enter the URL http://localhost:2001/set-cookie, your browser should display a page like the one in Figure 26-8. Additionally, the server will send a Set-Cookie header with a cookie named "MyCookie" with "A cookie value" as its value. If you click the link Look at cookie jar , you'll be taken to the /show-cookiespage where you'll see the new cookie, as shown in Figure 26-9. Because you didn't specify an :expiresargument, the browser will continue to send the cookie with each request until you quit the browser.

Figure 268 httplocalhost2001setcookie Figure 269 - фото 18

Figure 26-8. http://localhost:2001/set-cookie

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Practical Common Lisp»

Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Practical Common Lisp»

Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x