Peter Siebel - Practical Common Lisp
Здесь есть возможность читать онлайн «Peter Siebel - Practical Common Lisp» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2005, ISBN: 2005, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Practical Common Lisp
- Автор:
- Издательство:Apress
- Жанр:
- Год:2005
- ISBN:1-59059-239-5
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 5
Practical Common Lisp: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Practical Common Lisp»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Practical Common Lisp — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Practical Common Lisp», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Now you can publish some files. Suppose you have a file hello.html
in the directory /tmp/html
with the following contents:
Hello, world!
You can publish it individually with the publish-file
function.
WEB> (publish-file :path "/hello.html" :file "/tmp/html/hello.html")
#
The :path
argument is the path that will appear in the URL requested by the browser, while the :file
argument is the name of the file in the file system. After evaluating the publish-file
expression, you can point your browser to http://localhost:2001/hello.html
, and it should display a page something like Figure 26-2.

Figure 26-2. http://localhost:2001/hello.html
You could also publish a whole directory tree of files using the publish-directory
function. First let's clear out the already published entity with the following call to publish-file
:
WEB> (publish-file :path "/hello.html" :remove t)
NIL
Now you can publish the whole /tmp/html/
directory (and all its subdirectories) with the publish-directory
function.
WEB> (publish-directory :prefix "/" :destination "/tmp/html/")
#
In this case, the :prefix
argument specifies the beginning of the path part of URLs that should be handled by this entity. Thus, if the server receives a request for http://localhost:2001/foo/bar.html
, the path is /foo/bar.html
, which starts with /
. This path is then translated to a filename by replacing the prefix, /
, with the destination, /tmp/html/
. Thus, the URL http://localhost:2001/hello.html
will still be translated into a request for the file /tmp/html/hello.html
.
Generating Dynamic Content with AllegroServe
Publishing entities that generate dynamic content is nearly as simple as publishing static content. The functions publish
and publish-prefix
are the dynamic analogs of publish-file
and publish-directory
. The basic idea of these two functions is that you publish a function that will be called to generate the response to a request for either a specific URL or any URL with a given prefix. The function will be called with two arguments: an object representing the request and the published entity. Most of time you don't need to do anything with the entity object except to pass it along to a couple macros I'll discuss in a moment. On the other hand, you'll use the request object to obtain information submitted by the browser—query parameters included in the URL or data posted using an HTML form.
For a trivial example of using a function to generate dynamic content, let's write a function that generates a page with a different random number each time it's requested.
(defun random-number (request entity)
(with-http-response (request entity :content-type "text/html")
(with-http-body (request entity)
(format
(request-reply-stream request)
"~@
~@
~@
Random number: ~d
~@
~@
~@
"
(random 1000)))))
The macros with-http-response
and with-http-body
are part of AllegroServe. The former starts the process of generating an HTTP response and can be used, as here, to specify things such as the type of content that will be returned. It also handles various parts of HTTP such as dealing with If-Modified-Since requests. The with-http-body
actually sends the HTTP response headers and then executes its body, which should contain code that generates the content of the reply. Within with-http-response
but before the with-http-body
, you can add or change HTTP headers to be sent in the reply. The function request-reply-stream
is also part of AllegroServe and returns the stream to which you should write output intended to be sent to the browser.
As this function shows, you can just use FORMAT
to print HTML to the stream returned by request-reply-stream
. In the next section, I'll show you more convenient ways to programmatically generate HTML. [288] The ~@ followed by a newline tells FORMAT to ignore whitespace after the newline, which allows you to indent your code nicely without adding a bunch of whitespace to the HTML. Since white-space is typically not significant in HTML, this doesn't matter to the browser, but it makes the generated HTML source look a bit nicer to humans.
Now you're ready to publish this function.
WEB> (publish :path "/random-number" :function 'random-number)
#
As it does in the publish-file
function, the :path
argument specifies the path part of the URL that will result in this function being invoked. The :function
argument specifies either the name or an actual function object. Using the name of a function, as shown here, allows you to redefine the function later without republishing and have AllegroServe use the new function definition. After evaluating the call to publish
, you can point your browser at http:// localhost:2001/random-number
to get a page with a random number on it, as shown in Figure 26-3.

Figure 26-3. http://localhost:2001/random-number
Generating HTML
Although using FORMAT
to emit HTML works fine for the simple pages I've discussed so far, as you start building more elaborate pages it'd be nice to have a more concise way to generate HTML. Several libraries are available for generating HTML from an s-expression representation including one, htmlgen, that's included with AllegroServe. In this chapter you'll use a library called FOO, [289] FOO is a recursive tautological acronym for FOO Outputs Output .
which is loosely modeled on Franz's htmlgen and whose implementation you'll look at in more detail in Chapters 30 and 31. For now, however, you just need to know how to use FOO.
Generating HTML from within Lisp is quite natural since s-expressions and HTML are essentially isomorphic. You can represent HTML elements with s-expressions by treating each element in HTML as a list "tagged" with an appropriate first element, such as a keyword symbol of the same name as the HTML tag. Thus, the HTML
foo
(:p "foo")
. Because HTML elements nest the same way lists in s-expressions do, this scheme extends to more complex HTML. For instance, this HTML:
Hello, world!
could be represented with the following s-expression:
(:html
(:head (:title "Hello"))
(:body (:p "Hello, world!")))
HTML elements with attributes complicate things a bit but not in an insurmountable way. FOO supports two ways of including attributes in a tag. One is to simply follow the first item of the list with keyword/value pairs. The first element that follows a keyword/value pair that's not itself a keyword symbol marks the beginning of the element's contents. Thus, you'd represent this HTML:
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.